<?php
/**
 * 日报
 */

namespace app\mp\admin;

use app\common\model\Group as GroupModel;
use app\system\admin\Admin;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\Target as TargetService;
use think\facade\Env;
use app\common\service\OrderDelivery as OrderDeliveryService;
use app\common\service\Daily;

class DailyV2 extends Admin
{

    protected $orderService;
    protected $orderSizeService;
    protected $orderDeliveryService;
    protected $todayLeftTime = 86400; // 今天剩余秒数

    public function initialize()
    {
        parent::initialize();
        $this->orderService = new OrderService();
        $this->orderSizeService = new OrderSizeService();
        $this->orderDeliveryService = new OrderDeliveryService();
    }

    public function index()
    {
        $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $detail = $this->request->param('detail/d', 0);
        if (FACTORY_IDS != '*' && $factoryId != 0 && !in_array($factoryId, explode(',', FACTORY_IDS)) || !array_key_exists($from, config('mimo.order_from')) && $from != 0) {
            return $this->error('非法访问！');
        }

        $this->todayLeftTime = strtotime(date('Y-m-d 23:59:59')) - time();
        $this->view->engine->layout('system@layout_full');
        $factoryKV = getFactoryKV();

        if ($this->request->isAjax()) {
            $fun = $this->request->param('fun/s');
            $res = $this->$fun();

            if ($detail > 0) {
                $factoryKV = ['0' => '未分配'] + $factoryKV;
                $hisiCurMenu = ['title' => '订单列表'];
                $this->assign('hisiHead', '');
                return $this->assign(['hisiCurMenu' => $hisiCurMenu, 'list' => $res, 'factoryKV' => $factoryKV])->fetch('detail');
            } else {
                return $this->Json(1, '操作成功', $res);
            }
        }

        if (FACTORY_IDS == '*') {
            $factoryKV = ['0' => '全部工厂'] + $factoryKV;
        } elseif ($factoryId == 0) {
            $factoryId = key($factoryKV);
        }

        $assign = [
            'thisFactoryId' => $factoryId,
            'factoryKV' => $factoryKV,
            'thisFrom' => $from,
            'fromKV' => ['0' => '全部'] + config('mimo.order_from'),
        ];
        if ($this->request->param('pwd', 0) == '2') {
            return $this->assign($assign)->fetch('index_2');
        }
        return $this->assign($assign)->fetch();
    }

    /**
     * 产能分析
     *
     * @author KING
     * @date 2019年7月11日
     *
     */
    private function _getCnfx()
    {
        $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $detail = $this->request->param('detail/d', 0);
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);

        // 订单列表
        if ($detail > 0) {
            return $this->orderService->getOutputIng($factoryId, $from, true);
        }

        $cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from;

        // 7日平均日产能
        $output7Arr = cache(STAT_OUTPUT_AVG7 . $cacheSuffix);
        if (empty($output7Arr)) $output7Arr = $this->orderService->getOutputByDays(7, $factoryId, $from);
        cache(STAT_OUTPUT_AVG7 . $cacheSuffix, $output7Arr, $this->todayLeftTime);
        $result['recently7']['jianshu'] = $output7Arr['avgJianshu'];
        $result['recently7']['money'] = $output7Arr['avgMoney'];

        // 14日平均日产能
        $output14Arr = cache(STAT_OUTPUT_AVG14 . $cacheSuffix);
        if (empty($output14Arr)) $output14Arr = $this->orderService->getOutputByDays(14, $factoryId, $from);
        cache(STAT_OUTPUT_AVG14 . $cacheSuffix, $output14Arr, $this->todayLeftTime);
        $result['recently14']['jianshu'] = $output14Arr['avgJianshu'];
        $result['recently14']['money'] = $output14Arr['avgMoney'];

        // 21日平均日产能
        $output21Arr = cache(STAT_OUTPUT_AVG21 . $cacheSuffix);
        if (empty($output21Arr)) $output21Arr = $this->orderService->getOutputByDays(21, $factoryId, $from);
        cache(STAT_OUTPUT_AVG21 . $cacheSuffix, $output21Arr, $this->todayLeftTime);
        $result['recently21']['jianshu'] = $output21Arr['avgJianshu'];
        $result['recently21']['money'] = $output21Arr['avgMoney'];

        // 在途产能(不含已打包的)
        $outputIngArr = $this->orderService->getOutputIng($factoryId, $from);
        $result['recentlyIng']['jianshu'] = $outputIngArr['jianshu'];
        $result['recentlyIng']['orders'] = $outputIngArr['orders'];
        $result['recentlyIng']['money'] = $outputIngArr['money'];

        // 压力系数(在途（件）/21日平均，在途（元）/21日平均)
        $result['pressureRate']['jianshu'] = $result['recently21']['jianshu'] ? round($result['recentlyIng']['jianshu'] / $result['recently21']['jianshu'], 2) : 0;
        $result['pressureRate']['money'] = $result['recently21']['money'] ? round($result['recentlyIng']['money'] / $result['recently21']['money'], 2) : 0;

        return $result;
    }

    /**
     * 各厂产能分析
     *
     * @author KING
     * @date 2020年4月16日
     *
     */
    private function _getGccnfx()
    {
        $from = $this->request->param('from/d', 0);
        $data = [];
        $factoryList = getFactoryKV(true);

        foreach ($factoryList as $factoryId => $factoryName) {
            $cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from;

            $result = [];
            // 在途产能
            $result['recentlyIng']['jianshu'] = $this->orderService->getIngCountByRange($factoryId, '', $from);
            $result['recentlyIng']['money'] = $this->orderService->getIngMoneyByRange($factoryId, '', $from);

            // 最近21日均量/压力
            $output21Arr = cache(STAT_OUTPUT_AVG21 . $cacheSuffix);
            if (empty($output21Arr)) $output21Arr = $this->orderService->getOutputByDays(21, $factoryId, $from);
            cache(STAT_OUTPUT_AVG21 . $cacheSuffix, $output21Arr, $this->todayLeftTime);
            $result['recently21']['jianshu'] = $output21Arr['avgJianshu'];
            $result['recently21']['money'] = $output21Arr['avgMoney'];
            // 压力系数(在途（件）/21日平均，在途（元）/21日平均)
            $result['recently21']['jianshuPressure'] = $result['recently21']['jianshu'] ? round($result['recentlyIng']['jianshu'] / $result['recently21']['jianshu']) : 0;
            $result['recently21']['moneyPressure'] = $result['recently21']['money'] ? round($result['recentlyIng']['money'] / $result['recently21']['money']) : 0;

            // 最近7日均量/压力
            $output7Arr = cache(STAT_OUTPUT_AVG7 . $cacheSuffix);
            if (empty($output7Arr)) $output7Arr = $this->orderService->getOutputByDays(7, $factoryId, $from);
            cache(STAT_OUTPUT_AVG7 . $cacheSuffix, $output7Arr, $this->todayLeftTime);
            $result['recently7']['jianshu'] = $output7Arr['avgJianshu'];
            $result['recently7']['money'] = $output7Arr['avgMoney'];
            // 压力系数(在途（件）/7日平均，在途（元）/7日平均)
            $result['recently7']['jianshuPressure'] = $result['recently7']['jianshu'] ? round($result['recentlyIng']['jianshu'] / $result['recently7']['jianshu']) : 0;
            $result['recently7']['moneyPressure'] = $result['recently7']['money'] ? round($result['recentlyIng']['money'] / $result['recently7']['money']) : 0;

            // 最近4日出货、加工费、下单（昨天，前天，大前天，大大前天）
            $dayStart = strtotime('-1 day 00:00:00');
            $dayEnd = $dayStart + 86400;
            $recently1Arr = cache(STAT_OUTGO_DAYAGO1 . $cacheSuffix);
            if (empty($recently1Arr)) {
                $recently1Arr['recently1']['jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 昨天
                $recently1Arr['recently1']['money'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 昨天
                $recently1Arr['recently1']['orders'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 昨天
            }
            cache(STAT_OUTGO_DAYAGO1 . $cacheSuffix, $recently1Arr, $this->todayLeftTime);
            $result = array_merge($result, $recently1Arr);

            $dayStart = strtotime('-2 day 00:00:00');
            $dayEnd = $dayStart + 86400;
            $recently2Arr = cache(STAT_OUTGO_DAYAGO2 . $cacheSuffix);
            if (empty($recently2Arr)) {
                $recently2Arr['recently2']['jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 前天
                $recently2Arr['recently2']['money'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 前天
                $recently2Arr['recently2']['orders'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 前天
            }
            cache(STAT_OUTGO_DAYAGO2 . $cacheSuffix, $recently2Arr, $this->todayLeftTime);
            $result = array_merge($result, $recently2Arr);

            $dayStart = strtotime('-3 day 00:00:00');
            $dayEnd = $dayStart + 86400;
            $recently3Arr = cache(STAT_OUTGO_DAYAGO3 . $cacheSuffix);
            if (empty($recently3Arr)) {
                $recently3Arr['recently3']['jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 大前天
                $recently3Arr['recently3']['money'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 大前天
                $recently3Arr['recently3']['orders'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 大前天
            }
            cache(STAT_OUTGO_DAYAGO3 . $cacheSuffix, $recently3Arr, $this->todayLeftTime);
            $result = array_merge($result, $recently3Arr);

            $dayStart = strtotime('-4 day 00:00:00');
            $dayEnd = $dayStart + 86400;
            $recently4Arr = cache(STAT_OUTGO_DAYAGO4 . $cacheSuffix);
            if (empty($recently4Arr)) {
                $recently4Arr['recently4']['jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 大大前天
                $recently4Arr['recently4']['money'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 大大前天
                $recently4Arr['recently4']['orders'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);    // 大大前天
            }
            cache(STAT_OUTGO_DAYAGO4 . $cacheSuffix, $recently4Arr, $this->todayLeftTime);
            $result = array_merge($result, $recently4Arr);

            // 最近4日下单均量
            $dayStart = strtotime('-4 day 00:00:00');
            $dayEnd = $dayStart + 4 * 86400;
            $recently4avgArr = cache(STAT_RECENTLY4AVG_ORDER . $cacheSuffix);
            if (empty($recently4avgArr)) {
                $recently4avgArr['recently4avg']['orders'] = round(($result['recently1']['orders'] + $result['recently2']['orders'] + $result['recently3']['orders'] + $result['recently4']['orders']) / 4);
                $recently4avgArr['recently4avg']['money'] = round($this->orderService->getOrderMoneyAllByRange($dayStart, $dayEnd, $factoryId, '', $from) / 4);
            }
            cache(STAT_RECENTLY4AVG_ORDER . $cacheSuffix, $recently4avgArr, $this->todayLeftTime);
            $result = array_merge($result, $recently4avgArr);

            // 最近7日下单均量
            $dayStart = strtotime('-7 day 00:00:00');
            $dayEnd = $dayStart + 7 * 86400;
            $recently7avgArr = cache(STAT_RECENTLY7AVG_ORDER . $cacheSuffix);
            if (empty($recently7avgArr)) {
                $recently7avgArr['recently7avg']['orders'] = round($this->orderService->getOrderCountAllByRange($dayStart, $dayEnd, $factoryId, '', $from) / 7);
                $recently7avgArr['recently7avg']['money'] = round($this->orderService->getOrderMoneyAllByRange($dayStart, $dayEnd, $factoryId, '', $from) / 7);
            }
            cache(STAT_RECENTLY7AVG_ORDER . $cacheSuffix, $recently7avgArr, $this->todayLeftTime);
            $result = array_merge($result, $recently7avgArr);

            // 采购后在途产能/压力
            $result['afterPurchasingIng']['jianshu'] = $this->orderService->getIngCountByRange($factoryId, "o.caigou_status = 1", $from);
            $result['afterPurchasingIng']['money'] = $this->orderService->getIngMoneyByRange($factoryId, "o.caigou_status = 1", $from);
            $result['afterPurchasingIng']['jianshuPressure'] = $result['recently21']['jianshu'] ? round($result['afterPurchasingIng']['jianshu'] / $result['recently21']['jianshu']) : 0;
            $result['afterPurchasingIng']['moneyPressure'] = $result['recently21']['money'] ? round($result['afterPurchasingIng']['money'] / $result['recently21']['money']) : 0;

            // 外发产能（上月）
            $lastMonthStart = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
            $lastMonthEnd = strtotime(date("Y-m-1 00:00:00"));
            $lastMonthData = cache(STAT_OUTGO_LASTMONTH . $cacheSuffix);
            if (empty($lastMonthData)) {
                $lastMonthData['lastMonth']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($lastMonthStart, $lastMonthEnd, $factoryId, '', $from);    // 上月件数
                $lastMonthData['lastMonth']['money'] = $this->orderSizeService->getDaohuoMoneyByRange($lastMonthStart, $lastMonthEnd, $factoryId, '', $from);    // 上月金额
                $lastMonthData['lastMonthOutgo']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($lastMonthStart, $lastMonthEnd, $factoryId, "o.outgo_status > 0", $from);    // 上月外发件数
                $lastMonthData['lastMonthOutgo']['money'] = $this->orderSizeService->getDaohuoMoneyByRange($lastMonthStart, $lastMonthEnd, $factoryId, "o.outgo_status > 0", $from);    // 上月外发金额
                $lastMonthData['lastMonthOutgoRate']['jianshu'] = $lastMonthData['lastMonth']['jianshu'] ? round($lastMonthData['lastMonthOutgo']['jianshu'] * 100 / $lastMonthData['lastMonth']['jianshu']) . "%" : '0%';
                $lastMonthData['lastMonthOutgoRate']['money'] = $lastMonthData['lastMonth']['money'] ? round($lastMonthData['lastMonthOutgo']['money'] * 100 / $lastMonthData['lastMonth']['money']) . "%" : '0%';
            }
            cache(STAT_OUTGO_LASTMONTH . $cacheSuffix, $lastMonthData, $this->todayLeftTime);
            $result = array_merge($result, $lastMonthData);

            // 外发产能（本月）
            $thisMonthStart = strtotime(date("Y-m-1 00:00:00"));
            $thisMonthEnd = time();
            $result['thisMonth']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($thisMonthStart, $thisMonthEnd, $factoryId, '', $from);    // 本月件数
            $result['thisMonth']['money'] = $this->orderSizeService->getDaohuoMoneyByRange($thisMonthStart, $thisMonthEnd, $factoryId, '', $from);    // 本月金额
            $result['thisMonthOutgo']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($thisMonthStart, $thisMonthEnd, $factoryId, "o.outgo_status > 0", $from);    // 本月外发件数
            $result['thisMonthOutgo']['money'] = $this->orderSizeService->getDaohuoMoneyByRange($thisMonthStart, $thisMonthEnd, $factoryId, "o.outgo_status > 0", $from);    // 本月外发金额
            $result['thisMonthOutgoRate']['jianshu'] = $result['thisMonth']['jianshu'] ? round($result['thisMonthOutgo']['jianshu'] * 100 / $result['thisMonth']['jianshu']) . "%" : '0%';
            $result['thisMonthOutgoRate']['money'] = $result['thisMonth']['money'] ? round($result['thisMonthOutgo']['money'] * 100 / $result['thisMonth']['money']) . "%" : '0%';

            $data[$factoryId] = $result;
        }
        return $data;
    }

    /**
     * 获取不同环节近7天的完成件数
     *
     * @author KING
     * @date 2020年4月17日
     *
     */
    private function _getChart7daysJianshu()
    {
        $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);
        $step = $this->request->param('step/s', '');

        $days = [];
        $stepName = ['cg' => '采购', 'ml' => '面料处理', 'cj' => '裁剪', 'chej' => '车间', 'wb' => '尾部'];
        for ($i = 7; $i >= 1; $i--) {
            $dayStart = strtotime("-{$i} day 00:00:00");
            $dayEnd = $dayStart + 86400;

            $days[] = date("m月d日", $dayStart);

            if ($step == 'cg') {
                $list[] = $this->orderSizeService->getCountByRange($dayStart, $dayEnd, $factoryId, "", "o.caigou_over_time", "os.order_count", $from);
            } elseif ($step == 'ml') {
                $list[] = $this->orderService->getQuantityByCondition($factoryId, "o.caichuang_can_do_time between {$dayStart} and {$dayEnd}", $from);
            } elseif ($step == 'cj') {
                $list[] = $this->orderSizeService->getShicaiCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
            } elseif ($step == 'chej') {
                $list[] = $this->orderSizeService->getJiaohuoCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
            } elseif ($step == 'wb') {
                $list[] = $this->orderSizeService->getDaohuoCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
            }
        }

        $avg = round(array_sum($list) / 7);

        $stat[] = [
            'name' => '完成件数',
            'data' => $list,
        ];

        $result = ['days' => $days, 'stat' => $stat, 'stepName' => $stepName[$step], 'avg' => $avg];
        return $result;
    }

    /**
     * 订单进度
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getDdjd()
    {
        $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $detail = $this->request->param('detail/d', 0);
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);
        $cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from;

        // 订单列表
        if ($detail > 0) {
            $orderIds = [];
            if ($detail == 1) $orderIds = cache(STAT_CG . $cacheSuffix);
            elseif ($detail == 2) $orderIds = cache(STAT_ML . $cacheSuffix);
            elseif ($detail == 3) $orderIds = cache(STAT_CJ . $cacheSuffix);
            elseif ($detail == 4) $orderIds = cache(STAT_CHEJ . $cacheSuffix);
            elseif ($detail == 5) $orderIds = cache(STAT_WB . $cacheSuffix);
            elseif ($detail == 6) $orderIds = cache(STAT_DCH . $cacheSuffix);
            $fieldStatus = "(case when o.status=99 then '已废弃' when o.status=2 then '已完成' when o.tail_status=1 then '已打包' when o.chejian_status=1 then '已车缝' when o.caichuang_status=1 then '已裁剪' when o.caigou_status=1 then '已采购' else '采购中' end) as status_txt";
            $field = 'o.id,o.client_ordernum,o.factory_id,o.quantity,o.create_time,' . $fieldStatus;
            return db('order o')->where('id', 'in', $orderIds)->field($field)->order('create_time desc')->select();
        }

        // 统计数据
        $stat = $this->orderService->getOrderStat($factoryId, $from);

        // 昨日数据
        $dayStart = strtotime('-1 day 00:00:00');
        $dayEnd = $dayStart + 86400;

        // 【采购中】
        $yestodayCgArr = cache(STAT_DDJD_YESTODAY_CG . $cacheSuffix);
        if (empty($yestodayCgArr)) {
            $yestodayCgArr['yestoday']['cg']['jianshu'] = $this->orderService->getIngCountByRange($factoryId, "o.caigou_status = 1 and o.caigou_over_time > {$dayStart} and o.caigou_over_time < {$dayEnd}", $from);
            $yestodayCgArr['yestoday']['cg']['order'] = $this->orderService->getIngOrderByRange($factoryId, "o.caigou_status = 1 and o.caigou_over_time > {$dayStart} and o.caigou_over_time < {$dayEnd}", $from);
        }
        cache(STAT_DDJD_YESTODAY_CG . $cacheSuffix, $yestodayCgArr, $this->todayLeftTime);
        $stat = array_merge_recursive($stat, $yestodayCgArr);

        // 【面料处理】最大客户用料的面料已到料且未开始裁剪
        $yestodayMlArr = cache(STAT_DDJD_YESTODAY_ML . $cacheSuffix);
        if (empty($yestodayMlArr)) {
            $where = [
                ['status', 'in', [0, 1]],
                ['caichuang_status', '=', 0],
                ['caichuang_can_do', '=', 0],
            ];
            if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
            $mlList = db('order')->where($where)->where('id', 'IN', function ($query) use ($dayStart, $dayEnd) {
                $query->table(Env::get('database.prefix', 'wx_') . 'order_material')->where("caichuang_standard = 1 and arrive_time between {$dayStart} and {$dayEnd}")->field('order_id');
            })->field('id,quantity')->select();
            $mlCount = array_sum(array_column($mlList, 'quantity'));
            $mlOrder = count($mlList);
            $yestodayMlArr['yestoday']['ml']['jianshu'] = $mlCount;
            $yestodayMlArr['yestoday']['ml']['order'] = $mlOrder;
        }
        cache(STAT_DDJD_YESTODAY_ML . $cacheSuffix, $yestodayMlArr, $this->todayLeftTime);
        $stat = array_merge_recursive($stat, $yestodayMlArr);

        // 【裁剪】
        $yestodayCjArr = cache(STAT_DDJD_YESTODAY_CJ . $cacheSuffix);
        if (empty($yestodayCjArr)) {
            $yestodayCjArr['yestoday']['cj']['jianshu'] = $this->orderSizeService->getShicaiCountByRange($dayStart, $dayEnd, $factoryId, '', $from, true);
            $yestodayCjArr['yestoday']['cj']['order'] = $this->orderService->getOrdersByCondition($factoryId, "o.caichuang_status = 1 and o.caichuang_over_time > {$dayStart} and o.caichuang_over_time < {$dayEnd} and o.stock_type not in (10,11)", $from);
        }
        cache(STAT_DDJD_YESTODAY_CJ . $cacheSuffix, $yestodayCjArr, $this->todayLeftTime);
        $stat = array_merge_recursive($stat, $yestodayCjArr);

        // 【车间】
        $yestodayChejArr = cache(STAT_DDJD_YESTODAY_CHEJ . $cacheSuffix);
        if (empty($yestodayChejArr)) {
            $yestodayChejArr['yestoday']['chej']['jianshu'] = $this->orderSizeService->getJiaohuoCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
            $yestodayChejArr['yestoday']['chej']['order'] = $this->orderService->getOrdersByCondition($factoryId, "o.chejian_status = 1 and o.chejian_over_time > {$dayStart} and o.chejian_over_time < {$dayEnd}", $from);
        }
        cache(STAT_DDJD_YESTODAY_CHEJ . $cacheSuffix, $yestodayChejArr, $this->todayLeftTime);
        $stat = array_merge_recursive($stat, $yestodayChejArr);

        // 【尾部】
        $yestodayWbArr = cache(STAT_DDJD_YESTODAY_WB . $cacheSuffix);
        if (empty($yestodayWbArr)) {
            $yestodayWbArr['yestoday']['wb']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
            $yestodayWbArr['yestoday']['wb']['order'] = $this->orderService->getOrdersByCondition($factoryId, "o.tail_status = 1 and o.tail_over_time > {$dayStart} and o.tail_over_time < {$dayEnd}", $from);
        }
        cache(STAT_DDJD_YESTODAY_WB . $cacheSuffix, $yestodayWbArr, $this->todayLeftTime);
        $stat = array_merge_recursive($stat, $yestodayWbArr);

        $stat['update_time'] = date("Y年m月d日 H时i分");
        return $stat;
    }

    /**
     * 12天出货趋势分析图表
     *
     * @author KING
     * @date 2019年7月11日
     *
     */
    private function _getChqsfx()
    {
        $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);
        $factoryKV = ['0' => '全部工厂'] + getFactoryKV(true);

        $day = 12;
        $stat = $data = [];
        $days = [];
        for ($i = 0; $i < $day; $i++) {
            $dayStart = strtotime("+{$i} day 00:00:00");
            $dayEnd = $dayStart + 86399;
            $days[$i] = date("m月d日", $dayStart);

            $andWhere = [
                ['status', 'in', [0, 1]],
                ['shipment_time', 'between', [$dayStart, $dayEnd]],
            ];
            $data1[$i] = $this->orderService->getQuantityByCondition($factoryId, $andWhere, $from);
        }
        // 件数
        $stat[] = [
            'name' => arrayGet($factoryKV, $factoryId),
            'data' => $data1,
        ];

        return ['days' => $days, 'stat' => $stat];
    }

    /**
     * 12天出货趋势分析图表-订单列表
     *
     * @author KING
     * @date 2019年7月12日
     *
     */
    private function _getChqsfxDetail()
    {
        $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);
        $day = $this->request->param('day/s', '');
        $day = str_replace('月', '-', $day);
        $day = str_replace('日', '', $day);

        $dayArr = explode('-', $day);
        if ($dayArr[0] == '01' && date('m') == 12) {
            $day = (date('Y') + 1) . '-' . $day;
        } else {
            $day = date('Y') . '-' . $day;
        }

        $dayStart = strtotime($day . ' 00:00:00');
        $dayEnd = $dayStart + 86399;

        // 采购
        $where = [
            ['o.status', 'in', [0, 1]],
            ['o.caigou_status', '=', 0],
            ['o.shipment_time', 'between', [$dayStart, $dayEnd]],
        ];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        $list = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->field('o.*,s.ori_pic as pic')->order('o.shipment_time asc')->select();
        $resultCaiGou = [];
        foreach ($list as $key => $item) {
            $resultCaiGou[$key]['order_id'] = $item['id'];
            $resultCaiGou[$key]['tag'] = getOrderTag($item);
            $resultCaiGou[$key]['pic'] = $item['pic'];
            $resultCaiGou[$key]['client_ordernum'] = $item['client_ordernum'];
            $resultCaiGou[$key]['sku'] = $item['sku'];
            $resultCaiGou[$key]['num'] = $item['quantity'];
        }

        // 裁床
        $where = [
            ['o.status', 'in', [0, 1]],
            ['o.caigou_status', '=', 1],
            ['o.caichuang_status', '=', 0],
            ['o.shipment_time', 'between', [$dayStart, $dayEnd]],
        ];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        $list = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->field('o.*,s.ori_pic as pic')->order('o.shipment_time asc')->select();
        $resultCaiChuang = [];
        foreach ($list as $key => $item) {
            $resultCaiChuang[$key]['order_id'] = $item['id'];
            $resultCaiChuang[$key]['tag'] = getOrderTag($item);
            $resultCaiChuang[$key]['pic'] = $item['pic'];
            $resultCaiChuang[$key]['client_ordernum'] = $item['client_ordernum'];
            $resultCaiChuang[$key]['sku'] = $item['sku'];
            $resultCaiChuang[$key]['num'] = $item['quantity'];
        }

        // 车间
        $where = [
            ['o.status', 'in', [0, 1]],
            ['o.caichuang_status', '=', 1],
            ['o.chejian_status', '=', 0],
            ['o.shipment_time', 'between', [$dayStart, $dayEnd]],
        ];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];

        $list = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->field('o.*,s.ori_pic as pic')->order('o.shipment_time asc')->select();
        $resultCheJian = [];

        foreach ($list as $key => $item) {
            $resultCheJian[$key]['order_id'] = $item['id'];
            $resultCheJian[$key]['tag'] = getOrderTag($item);
            $resultCheJian[$key]['pic'] = $item['pic'];
            $resultCheJian[$key]['client_ordernum'] = $item['client_ordernum'];
            $resultCheJian[$key]['sku'] = $item['sku'];
            $resultCheJian[$key]['num'] = $item['quantity'];
        }

        // 尾部
        $where = [
            ['o.status', 'in', [0, 1]],
            ['o.chejian_status', '=', 1],
            ['o.tail_status', '=', 0],
            ['o.shipment_time', 'between', [$dayStart, $dayEnd]],
        ];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        $list = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->field('o.*,s.ori_pic as pic')->order('o.shipment_time asc')->select();
        $resultTail = [];
        foreach ($list as $key => $item) {
            $resultTail[$key]['order_id'] = $item['id'];
            $resultTail[$key]['tag'] = getOrderTag($item);
            $resultTail[$key]['pic'] = $item['pic'];
            $resultTail[$key]['client_ordernum'] = $item['client_ordernum'];
            $resultTail[$key]['sku'] = $item['sku'];
            $resultTail[$key]['num'] = $item['quantity'];
        }
        return ['caigou' => $resultCaiGou, 'caichuang' => $resultCaiChuang, 'chejian' => $resultCheJian, 'tail' => $resultTail];
    }

    /**
     * 上月本月昨日今日出货统计图表
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getChartMonthChtj()
    {
        $from = $this->request->param('from/d', 0);
        $factoryKV = ['0' => '全部工厂'] + getFactoryKV(true);
        $factoryId = $this->request->param('factory_id/d', 0);
        $detail = $this->request->param('detail/d', 0);

        $factoryName = arrayGet($factoryKV, $factoryId, '');
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);
        $cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from;

        // 订单列表
        if ($detail > 0) {
            $fieldStatus = "(case when o.status=99 then '已废弃' when o.status=2 then '已完成' when o.tail_status=1 then '已打包' when o.chejian_status=1 then '已车缝' when o.caichuang_status=1 then '已裁剪' when o.caigou_status=1 then '已采购' else '采购中' end) as status_txt";
            $groupBy = "o.id,o.factory_id,o.client_ordernum,o.create_time,o.status,o.tail_status,o.chejian_status,o.caichuang_status,o.caigou_status";
            if ($detail == 1) { // 上月出货订单
                $orderDeliveryIds = cache(STAT_CHTJ_LASTMONTH . $cacheSuffix);
                $field = 'o.id,o.client_ordernum,o.factory_id,sum(od.real_shipment_count) as quantity,o.create_time,' . $fieldStatus;
                return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('o.create_time desc')->select();
            } elseif ($detail == 2) { // 上月入仓订单
                $orderDeliveryIds = cache(STAT_RCTJ_LASTMONTH . $cacheSuffix);
                $field = 'o.id,o.client_ordernum,o.factory_id,sum(od.store_count) as quantity,o.create_time,' . $fieldStatus;
                return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('o.create_time desc')->select();
            } elseif ($detail == 3) { // 本月出货订单
                $orderDeliveryIds = cache(STAT_CHTJ_THISMONTH . $cacheSuffix);
                $field = 'o.id,o.client_ordernum,o.factory_id,sum(od.real_shipment_count) as quantity,o.create_time,' . $fieldStatus;
                return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('create_time desc')->select();
            } elseif ($detail == 4) { // 本月入仓订单
                $orderDeliveryIds = cache(STAT_RCTJ_THISMONTH . $cacheSuffix);
                $field = 'o.id,o.client_ordernum,o.factory_id,sum(od.store_count) as quantity,o.create_time,' . $fieldStatus;
                return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('create_time desc')->select();
            } elseif ($detail == 5) { // 昨日出货订单
                $orderDeliveryIds = cache(STAT_CHTJ_YESTODAY_SHIPMENT . $cacheSuffix);
                $field = 'o.id,o.client_ordernum,o.factory_id,sum(od.real_shipment_count) as quantity,o.create_time,' . $fieldStatus;
                return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('create_time desc')->select();
            } elseif ($detail == 6) { // 昨日入仓订单
                $orderDeliveryIds = cache(STAT_CHTJ_YESTODAY_STORE . $cacheSuffix);
                $field = 'o.id,o.client_ordernum,o.factory_id,sum(od.store_count) as quantity,o.create_time,' . $fieldStatus;
                return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('create_time desc')->select();
            }
        }

        $data = [];
        $stat = [];

        // 上月累计出货（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
        $lastMonthStart = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
        $lastMonthEnd = strtotime(date("Y-m-1 00:00:00"));
        $where = [
            ['o.status', '<>', 99],
            ['od.delivery_status', 'not in', [6, 7]],
            ['od.delivery_time', 'between', [$lastMonthStart, $lastMonthEnd]],
        ];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        $moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
        $moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
        $jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.real_shipment_count');
        $orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
        $orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
        cache(STAT_CHTJ_LASTMONTH . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
        $stat['last_month']['fob'][] = [
            "name" => "出货",
            "data" => [floatval($moneyFob)],
        ];
        $stat['last_month']['cost'][] = [
            "name" => "出货",
            "data" => [floatval($moneyCost)],
        ];
        $stat['last_month']['jianshu'][] = [
            "name" => "出货",
            "data" => [$jianshuTotal],
        ];
        $stat['last_month']['orders'][] = [
            "name" => "出货",
            "data" => [$orderCount],
        ];

        // 上月累计入仓（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
        $lastMonthStart = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
        $lastMonthEnd = strtotime(date("Y-m-1 00:00:00"));
        $where = [
            ['o.status', '<>', 99],
            ['od.delivery_status', '=', 8],
            ['od.store_time', 'between', [$lastMonthStart, $lastMonthEnd]],
        ];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        $moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
        $moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
        $jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.store_count');
        $orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
        $orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
        cache(STAT_RCTJ_LASTMONTH . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
        $stat['last_month']['fob'][] = [
            "name" => "入仓",
            "data" => [floatval($moneyFob)],
        ];
        $stat['last_month']['cost'][] = [
            "name" => "入仓",
            "data" => [floatval($moneyCost)],
        ];
        $stat['last_month']['jianshu'][] = [
            "name" => "入仓",
            "data" => [$jianshuTotal],
        ];
        $stat['last_month']['orders'][] = [
            "name" => "入仓",
            "data" => [$orderCount],
        ];

        // 本月累计出货（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
        $monthStart = strtotime(date("Y-m-1 00:00:00"));
        $where = [
            ['o.status', '<>', 99],
            ['od.delivery_status', 'not in', [6, 7]],
            ['od.delivery_time', '>=', $monthStart],
        ];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        $moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
        $moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
        $jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.real_shipment_count');
        $orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
        $orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
        cache(STAT_CHTJ_THISMONTH . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
        $stat['this_month']['fob'][] = [
            "name" => "出货",
            "data" => [floatval($moneyFob)],
        ];
        $stat['this_month']['cost'][] = [
            "name" => "出货",
            "data" => [floatval($moneyCost)],
        ];
        $stat['this_month']['jianshu'][] = [
            "name" => "出货",
            "data" => [$jianshuTotal],
        ];
        $stat['this_month']['orders'][] = [
            "name" => "出货",
            "data" => [$orderCount],
        ];

        // 本月累计入仓（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
        $monthStart = strtotime(date("Y-m-1 00:00:00"));
        $where = [
            ['o.status', '<>', 99],
            ['od.delivery_status', '=', 8],
            ['od.store_time', '>=', $monthStart],
        ];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        $moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
        $moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
        $jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.store_count');
        $orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
        $orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
        cache(STAT_RCTJ_THISMONTH . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
        $stat['this_month']['fob'][] = [
            "name" => "入仓",
            "data" => [floatval($moneyFob)],
        ];
        $stat['this_month']['cost'][] = [
            "name" => "入仓",
            "data" => [floatval($moneyCost)],
        ];
        $stat['this_month']['jianshu'][] = [
            "name" => "入仓",
            "data" => [$jianshuTotal],
        ];
        $stat['this_month']['orders'][] = [
            "name" => "入仓",
            "data" => [$orderCount],
        ];

        // 昨日出货（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
        $yestodayStart = strtotime("-1 day 00:00:00");
        $todayStart = strtotime("0 day 00:00:00");
        $where = [
            ['o.status', '<>', 99],
            ['od.delivery_status', 'not in', [6, 7]],
            ['od.delivery_time', 'between', [$yestodayStart, $todayStart]],
        ];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        $moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
        $moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
        $jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.real_shipment_count');
        $orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
        $orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
        cache(STAT_CHTJ_YESTODAY_SHIPMENT . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
        $stat['yestoday']['fob'][] = [
            "name" => "出货",
            "data" => [floatval($moneyFob)],
        ];
        $stat['yestoday']['cost'][] = [
            "name" => "出货",
            "data" => [floatval($moneyCost)],
        ];
        $stat['yestoday']['jianshu'][] = [
            "name" => "出货",
            "data" => [$jianshuTotal],
        ];
        $stat['yestoday']['orders'][] = [
            "name" => "出货",
            "data" => [$orderCount],
        ];

        // 昨日入仓（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
        $yestodayStart = strtotime("-1 day 00:00:00");
        $todayStart = strtotime("0 day 00:00:00");
        $where = [
            ['o.status', '<>', 99],
            ['od.delivery_status', '=', 8],
            ['od.store_time', 'between', [$yestodayStart, $todayStart]],
        ];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        $moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
        $moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
        $jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.store_count');
        $orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
        $orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
        cache(STAT_CHTJ_YESTODAY_STORE . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
        $stat['yestoday']['fob'][] = [
            "name" => "入仓",
            "data" => [floatval($moneyFob)],
        ];
        $stat['yestoday']['cost'][] = [
            "name" => "入仓",
            "data" => [floatval($moneyCost)],
        ];
        $stat['yestoday']['jianshu'][] = [
            "name" => "入仓",
            "data" => [$jianshuTotal],
        ];
        $stat['yestoday']['orders'][] = [
            "name" => "入仓",
            "data" => [$orderCount],
        ];

        // 昨日下单
        $yestodayStart = strtotime("-1 day 00:00:00");
        $todayStart = strtotime("0 day 00:00:00");
        $where = [
            ['o.status', 'in', [0, 1, 2]],
            ['o.create_time', 'between', [$yestodayStart, $todayStart]],
        ];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        $jianshuYestoday = db('order_size os')->join('order o', 'o.id=os.order_id')->where($where)->sum('os.order_count');

        // 今日下单
        $todayStart = strtotime("0 day 00:00:00");
        $where = [
            ['o.status', 'in', [0, 1, 2]],
            ['o.create_time', '>=', $todayStart],
        ];
        if ($from) $where[] = ['o.is_auto_import', '=', $from];
        if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        $jianshuToday = db('order_size os')->join('order o', 'o.id=os.order_id')->where($where)->sum('os.order_count');

        $stat['recent_2days'] = [
            ["name" => "昨日", "data" => [$jianshuYestoday]],
            ["name" => "今日", "data" => [$jianshuToday]],
        ];

        $targetService = new TargetService();

        // 本月目标
        $monthTargetCount = $targetService->getTarget($factoryId, 1);    // 件数
        $monthTargetMoney = $targetService->getTarget($factoryId, 2); // 金额
        $monthTargetCost = $targetService->getTarget($factoryId, 3); // 加工费

        // 完成度
        $monthData = $this->orderSizeService->getMonthCompleteData($factoryId, $from);
        $completenessCount = $monthTargetCount ? round($monthData['count'] * 100 / $monthTargetCount, 2) : 0;    // 件数
        $completenessmoney = $monthTargetMoney ? round($monthData['money'] * 100 / $monthTargetMoney, 2) : 0;    // 金额
        $completenessCost = $monthTargetCost ? round($monthData['cost'] * 100 / $monthTargetCost, 2) : 0;    // 加工费

        $stat['this_month_target']['fob'] = [
            "rate" => $completenessmoney,
            "series" => [
                ["name" => "目标", "data" => [round($monthData['money'])]],
                ["name" => "实际", "data" => [round($monthTargetMoney)]]
            ],
        ];
        $stat['this_month_target']['jianshu'] = [
            "rate" => $completenessCount,
            "series" => [
                ["name" => "目标", "data" => [intval($monthData['count'])]],
                ["name" => "实际", "data" => [intval($monthTargetCount)]]
            ],
        ];
        $stat['this_month_target']['cost'] = [
            "rate" => $completenessmoney,
            "series" => [
                ["name" => "目标", "data" => [round($monthData['cost'])]],
                ["name" => "实际", "data" => [round($monthTargetCost)]]
            ],
        ];

        // 货期
        $monthStart = strtotime(date("Y-m-1 00:00:00"));
        $where = [
            ['status', '=', 2],
            ['over_time', '>=', $monthStart],
        ];
        if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
        if ($from) $where[] = ['is_auto_import', '=', $from];
        $totalCount = db('order')->where($where)->sum('quantity'); // 总数
        $standardCount = db('order')->where($where)->where('is_standard', 1)->sum('quantity'); // 货期达标数
        $leadtimeTargetRate = ($totalCount) ? round($standardCount * 100 / $totalCount, 2) : 0;    // 达标率 = 本月已交付订单 货期达标/总数
        $leadtimeTarget = $targetService->getTarget($factoryId, 4); // 目标
        $stat['this_month_target']['leadtime'] = [
            "series" => [
                ["name" => "目标", "data" => [$leadtimeTarget]],
                ["name" => "实际", "data" => [$leadtimeTargetRate]]
            ],
        ];

        // 年度
        $yearTargetMoney = $this->orderSizeService->getYearMoney($factoryId, $from);    // 金额=本年1月1日起的 FOB+CMT+新CMT 的总出货金额
        $yearTarget = $targetService->getTarget($factoryId, 5); // 目标金额
        $yearTargetRate = !round($yearTarget, 2) ? '' : round($yearTargetMoney * 100 / $yearTarget, 2); // 完成率 = 已完成年度金额/年度目标金额

        $stat['year_target'] = [
            "rate" => $yearTargetRate,
            "series" => [
                ["name" => "目标", "data" => [$yearTarget]],
                ["name" => "金额", "data" => [$yearTargetMoney]]
            ],
        ];

        $data = [
            'stat' => $stat,
            'factory_id' => $factoryId,
            'factory_name' => $factoryName
        ];
        return $data;
    }

    /**
     * 下单情况统计
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getChOrSit()
    {
        $from = $this->request->param('from/d', 0);
        $sTime = microtime(true);
        $factoryId = $this->request->param('factory_id/d', 0);
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);
        $type = $this->request->param('type/d', 1);

        $cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from . '-' . $type;
        $statData = cache(STAT_CHORSIT . $cacheSuffix);
        if (!empty($statData)) return $statData;

        $jianshuOutTotalArr = $moneyArr = $costOutArr = $jianshuInTotalArr = $costInArr = $days = [];
        $timeStart = $day = '';
        if ($type == 1) {
            $timeStart = strtotime(date("Y-m-01 00:00:00"));
            $day = date('t', strtotime('-1 month 00:00:00'));
        } elseif ($type == 2) {
            $timeStart = time();
            $day = 10;
        }

        for ($i = $day; $i > 0; $i--) {
            $dayStart = strtotime("-{$i} day 00:00:00", $timeStart);
            $dayEnd = strtotime("-{$i} day 23:59:59", $timeStart);
            $days[] = date("m月d日", $dayStart);

            $where = [
                ['o.status', 'in', [0, 1, 2]],
                ['o.create_time', 'between', [$dayStart, $dayEnd]],
            ];
            if ($from) $where[] = ['o.is_auto_import', '=', $from];
            if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
            $row = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->fieldRaw("ifnull(sum(o.quantity),0) as jianshu,ifnull(count(o.client_ordernum),0) as counts,ifnull(sum(s.cost),0) as cost")->find();

            $jianshuInTotalArr[] = (float)arrayGet($row, 'jianshu', 0);    // 订单件数
            //$costInArr[] = (float)arrayGet($row, 'cost',0);		// 加工费
            $countsInArr[] = arrayGet($row, 'counts', 0);
            $costInArrAll[] = (float)round((arrayGet($row, 'cost', 0) * arrayGet($row, 'counts', 0)), 2);
        }
        //获取平均数
        $count = count(array_diff($jianshuInTotalArr, [0]));
        $jianshuInTotalArr[] = $count ? round(array_sum($jianshuInTotalArr) / $count) : 0;
        $costInArrAll[] = $count ? round(array_sum($costInArrAll) / $count, 2) : 0;
        $costInArr[] = $count ? round(array_sum($costInArr) / $count, 2) : 0;
        $countsInArr[] = $count ? round(array_sum($countsInArr) / $count) : 0;
        $days[] = '平均';
        $stat[0]['name'] = '订单件数';
        $stat[0]['data'] = $jianshuInTotalArr;
        $stat[1]['name'] = '总加工费';
        $stat[1]['data'] = $costInArrAll;
        $stat[2]['name'] = '订单数量';
        $stat[2]['data'] = $countsInArr;
        // $stat[3]['name'] = '加工费';
        // $stat[3]['data'] = $costInArr;

        $statData = ['days' => $days, 'list' => $stat, 'update_time' => date("Y年m月d日 H时i分")];
        cache(STAT_CHORSIT . $cacheSuffix, $statData, $this->todayLeftTime);
        return $statData;
    }

    /**
     * 车间生产压力统计
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getCjyl()
    {
        $from = $this->request->param('from/d', 0);
        $sTime = microtime(true);
        $factoryKV = ['0' => '全部工厂'] + getFactoryKV(true);
        $factoryId = $this->request->param('factory_id/d', 0);
        $factoryName = arrayGet($factoryKV, $factoryId, '');
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);

        $todayStart = strtotime('0 day 00:00:00');
        $monthStart = strtotime(date('Y-m-1 00:00:00'));
        $lastMonthStart = strtotime(date("Y-m-1 00:00:00", strtotime('-1 month 00:00:00')));

        $dayStart = strtotime('-21 day 00:00:00');
        $dayEnd = strtotime('0 day 00:00:00');

        $resList = [];
        if (is_numeric($factoryId)) {
            $groupKV = getGroupKV($factoryId);
        } else {
            $groupKV = db('group')->where('factory_id', 'in', $factoryId)->where('status', 1)->column('name', 'id');
        }

        $stat = [];
        foreach ($groupKV as $groupId => $groupName) {
            $cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from . '-' . $groupId;

            $stat[$groupId]['name'] = $groupName;

            // 应到
            $stat[$groupId]['yd'] = 0;
            $stat[$groupId]['sd'] = 0;

            // 本月出货件数、本月出货加工费
            $stat[$groupId]['month_jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($monthStart, time(), $factoryId, ['o.group_id' => $groupId], $from);
            $stat[$groupId]['month_cost'] = $this->orderDeliveryService->getRealShipmentCostByRange($monthStart, time(), $factoryId, ['o.group_id' => $groupId], $from);

            // 上月出货件数、上月出货加工费
            $statGroupLastMonthArr = cache(STAT_OUTGO_GROUP_LASTMONTH . $cacheSuffix);
            if (empty($statGroupLastMonthArr)) {
                $statGroupLastMonthArr['last_month_jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($lastMonthStart, $monthStart - 1, $factoryId, ['o.group_id' => $groupId], $from);
                $statGroupLastMonthArr['last_month_cost'] = $this->orderDeliveryService->getRealShipmentCostByRange($lastMonthStart, $monthStart - 1, $factoryId, ['o.group_id' => $groupId], $from);
            }
            cache(STAT_OUTGO_GROUP_LASTMONTH . $cacheSuffix, $statGroupLastMonthArr, $this->todayLeftTime);
            $stat[$groupId]['last_month_jianshu'] = arrayGet($statGroupLastMonthArr, 'last_month_jianshu', 0);
            $stat[$groupId]['last_month_cost'] = arrayGet($statGroupLastMonthArr, 'last_month_cost', 0);

            // 近21日 平均每日加工费
            $statCostGroupAvg21Data = cache(STAT_COST_GROUP_AVG21 . $cacheSuffix);
            if (empty($statCostGroupAvg21Data)) {
                $statCostGroupAvg21Data = round($this->orderSizeService->getDaohuoMoneyByRange($dayStart, $dayEnd, $factoryId, ['o.group_id' => $groupId], $from) / 21, 2);
            }
            cache(STAT_COST_GROUP_AVG21 . $cacheSuffix, $statCostGroupAvg21Data, $this->todayLeftTime);
            $stat[$groupId]['avg_cost'] = $statCostGroupAvg21Data;

            // 采购加工费
            $andWhere = [
                ['o.status', 'in', [0, 1]],
                ['o.caigou_status', '=', 0],
                ['o.group_id', '=', $groupId],
            ];
            $stat[$groupId]['caigou_cost'] = $this->orderService->getOrderMoneyAllByRange(0, time(), $factoryId, $andWhere, $from);

            // 裁剪加工费
            $andWhere = [
                ['o.status', 'in', [0, 1]],
                ['o.caigou_status', '=', 1],
                ['o.caichuang_status', '=', 0],
                ['o.group_id', '=', $groupId],
            ];
            $stat[$groupId]['caijian_cost'] = $this->orderService->getOrderMoneyAllByRange(0, time(), $factoryId, $andWhere, $from);

            // 车间生产压力
            // 总件数
            $andWhere = [
                ['o.status', 'in', [0, 1]],
                ['o.caichuang_status', '=', 1],
                ['o.chejian_status', '=', 0],
                ['o.group_id', '=', $groupId],
            ];
            $stat[$groupId]['jianshu_total'] = $this->orderService->getOrderCountAllByRange(0, time(), $factoryId, $andWhere, $from);
            // 总加工费
            $stat[$groupId]['money_total'] = $this->orderService->getOrderMoneyAllByRange(0, time(), $factoryId, $andWhere, $from);
        }

        if ($stat) {
            $resList[] = [
                'factory_id' => $factoryId,
                'factory_name' => $factoryName,
                'stat' => $stat
            ];
        }

        return ['list' => $resList, 'update_time' => date("Y年m月d日 H时i分")];
    }

    /**
     * 出货统计图表
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getChart()
    {
        $from = $this->request->param('from/d', 0);
        $sTime = microtime(true);
        $factoryId = $this->request->param('factory_id/d', 0);
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);
        $type = $this->request->param('type/d', 1);

        $cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from . '-' . $type;

        $statData = cache(STAT_SHIPMENT_CHART_DAYS30 . $cacheSuffix);
        if (!empty($statData)) return $statData;

        $jianshuOutTotalArr = $moneyArr = $costOutArr = $jianshuInTotalArr = $costInArr = $days = [];
        for ($i = 30; $i > 0; $i--) {
            $dayStart = strtotime("-{$i} day 00:00:00");
            $dayEnd = strtotime("-{$i} day 23:59:59");
            $days[] = date("m月d日", $dayStart);

            $where = [
                ['o.status', 'in', [0, 1, 2]],
                ['od.store_time', 'between', [$dayStart, $dayEnd]],
                ['od.delivery_status', 'not in', [6, 7]],
            ];
            if ($from) $where[] = ['o.is_auto_import', '=', $from];
            if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
            $row = db('order_delivery od')->join('order o', 'o.id = od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw("SUM(od.store_count) AS jianshu,SUM(od.store_count * s.cost) AS cost")->find();
            $jianshuInTotalArr[] = (float)arrayGet($row, 'jianshu', 0);    // 入货件数
            $costInArr[] = (float)arrayGet($row, 'cost', 0);        // 入货加工费

            // 出货件数、出货金额、出货加工费
            $where = [
                ['o.status', 'in', [0, 1, 2]],
                ['od.delivery_time', 'between', [$dayStart, $dayEnd]],
                ['od.delivery_status', 'not in', [6, 7]],
            ];
            if ($from) $where[] = ['o.is_auto_import', '=', $from];
            if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
            $list = db('order_delivery od')->join('order o', 'o.id = od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->field('s.price,s.cost,o.o_type,od.real_shipment_count')->select();
            $jianshuOutTotal = 0;
            $money = 0;
            $costOut = 0;
            foreach ($list as $k => $v) {
                $jianshu = $v['real_shipment_count'];
                $jianshuOutTotal += $jianshu;

                if ($v['o_type'] == 'FOB') $money += $jianshu * $v['price'];
                elseif ($v['o_type'] == 'CMT') $money += $jianshu * $v['cost'];
                elseif ($v['o_type'] == 'CMT2') $money += $jianshu * $v['cost'];

                $costOut += $jianshu * $v['cost'];
            }
            $jianshuOutTotalArr[] = $jianshuOutTotal;    // 出货件数
            $moneyArr[] = round($money);    // 出货金额
            $costOutArr[] = round($costOut);        // 出货加工费
        }

        if ($type == 1) {
            $stat[0]['name'] = '出货金额';
            $stat[0]['data'] = $moneyArr;
            $stat[1]['name'] = '出货加工费';
            $stat[1]['data'] = $costOutArr;
            $stat[2]['name'] = '入货加工费';
            $stat[2]['data'] = $costInArr;
        } elseif ($type == 2) {
            $stat[0]['name'] = '出货件数';
            $stat[0]['data'] = $jianshuOutTotalArr;
            $stat[1]['name'] = '入货件数';
            $stat[1]['data'] = $jianshuInTotalArr;
        }

        $statData = ['days' => $days, 'list' => $stat, 'update_time' => date("Y年m月d日 H时i分")];
        cache(STAT_SHIPMENT_CHART_DAYS30 . $cacheSuffix, $statData, $this->todayLeftTime);
        return $statData;
    }


    /**
     * 针织梭织统计
     *
     * @author KING
     * @date 2019年7月17日
     *
     */
    private function _getSkutypeStat()
    {
        $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $factoryId = $factoryId ? $factoryId : (FACTORY_IDS == '*' ? 0 : FACTORY_IDS);

        $days = [];
        $skuTypeArr = ['zz' => '针织', 'sz' => '梭织'];
        for ($i = 7; $i > 0; $i--) {
            $n = 7 - $i;
            $dayStart = strtotime("-{$i} day 00:00:00");
            $dayEnd = strtotime("-{$i} day 23:59:59");

            // 日期列表
            $days[] = date('n月j日', $dayStart);

            foreach ($skuTypeArr as $stk => $stv) {
                // 针织/梭织下单-成本费用
                $where = [
                    ['o.status', 'in', [0, 1, 2]],
                    ['o.create_time', 'between', [$dayStart, $dayEnd]],
                    ['s.sku_type', '=', $stv],
                ];
                if ($from) $where[] = ['o.is_auto_import', '=', $from];
                if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
                $orders[$stk][$n]['m'] = arrayGet(db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->fieldRaw('sum(o.quantity*s.cost) as num')->findOrEmpty(), 'num', 0, true);

                // 针织下单-下单件数
                $where = [
                    ['o.status', 'in', [0, 1, 2]],
                    ['o.create_time', 'between', [$dayStart, $dayEnd]],
                    ['s.sku_type', '=', $stv],
                ];
                if ($from) $where[] = ['o.is_auto_import', '=', $from];
                if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
                $orders[$stk][$n]['i'] = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->sum('o.quantity');

                // 针织/梭织下单-订单数
                $where = [
                    ['o.status', 'in', [0, 1, 2]],
                    ['o.create_time', 'between', [$dayStart, $dayEnd]],
                    ['s.sku_type', '=', $stv],
                ];
                if ($from) $where[] = ['o.is_auto_import', '=', $from];
                if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
                $orders[$stk][$n]['o'] = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->count('o.id');


                // 针织/梭织出货-成本费用
                $where = [
                    ['o.status', 'in', [0, 1, 2]],
                    ['o.shipment_time', 'between', [$dayStart, $dayEnd]],
                    ['s.sku_type', '=', $stv],
                ];
                if ($from) $where[] = ['o.is_auto_import', '=', $from];
                if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
                $shipments[$stk][$n]['m'] = arrayGet(db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->fieldRaw('sum(o.quantity*s.cost) as num')->findOrEmpty(), 'num', 0, true);

                // 针织/梭织出货-下单件数
                $where = [
                    ['o.status', 'in', [0, 1, 2]],
                    ['o.shipment_time', 'between', [$dayStart, $dayEnd]],
                    ['s.sku_type', '=', $stv],
                ];
                if ($from) $where[] = ['o.is_auto_import', '=', $from];
                if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
                $shipments[$stk][$n]['i'] = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->sum('o.quantity');

                // 针织/梭织出货-订单数
                $where = [
                    ['o.status', 'in', [0, 1, 2]],
                    ['o.shipment_time', 'between', [$dayStart, $dayEnd]],
                    ['s.sku_type', '=', $stv],
                ];
                if ($from) $where[] = ['o.is_auto_import', '=', $from];
                if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
                $shipments[$stk][$n]['o'] = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->count('o.id');
            }
        }

        $dayEnd = strtotime('0 day 00:00:00');
        $dayStartArr = [
            '7' => [strtotime('-7 day 00:00:00'), $dayEnd],
            '14' => [strtotime('-14 day 00:00:00'), $dayEnd],
            '21' => [strtotime('-21 day 00:00:00'), $dayEnd],
            '1' => [0, $dayEnd + 86400], // 在途
        ];

        foreach ($dayStartArr as $k => $dayRange) {
            $dayStart = $dayRange[0];
            $dayEnd = $dayRange[1];
            foreach ($skuTypeArr as $stk => $stv) {
                // 针织/梭织下单-成本费用
                if ($k != 1) {
                    $day[$stk][$k]['m'] = $this->orderService->getOrderMoneyAllByRange($dayStart, $dayEnd, $factoryId, ['s.sku_type' => $stv], $from);
                } else {
                    $andWhere = [
                        ['o.create_time', 'between', [$dayStart, $dayEnd]],
                        ['s.sku_type', '=', $stv],
                    ];
                    $day[$stk][$k]['m'] = $this->orderService->getIngMoneyByRange($factoryId, $andWhere, $from);
                }

                // 针织/梭织下单-下单件数
                if ($k != 1) {
                    $day[$stk][$k]['i'] = $this->orderService->getOrderCountAllByRange($dayStart, $dayEnd, $factoryId, ['s.sku_type' => $stv], $from);
                } else {
                    $andWhere = [
                        ['o.create_time', 'between', [$dayStart, $dayEnd]],
                        ['s.sku_type', '=', $stv],
                    ];
                    $day[$stk][$k]['i'] = $this->orderService->getIngCountByRange($factoryId, $andWhere, $from);
                }

                // 针织/梭织下单-订单数
                $andWhere = [
                    ['o.create_time', 'between', [$dayStart, $dayEnd]],
                    ['s.sku_type', '=', $stv],
                ];
                if ($k != 1) {
                    $day[$stk][$k]['o'] = $this->orderService->getOrdersByCondition($factoryId, $andWhere, $from);
                } else {
                    $day[$stk][$k]['o'] = $this->orderService->getIngOrderByRange($factoryId, $andWhere, $from);
                }
            }
        }

        // 压力系数(在途（件）/21日平均，在途（元）/21日平均)
        $pressureRate['zz']['m'] = $day['zz'][21]['m'] ? round($day['zz'][1]['m'] / $day['zz'][21]['m'], 2) : 0;
        $pressureRate['zz']['i'] = $day['zz'][21]['i'] ? round($day['zz'][1]['i'] / $day['zz'][21]['i'], 2) : 0;
        $pressureRate['zz']['o'] = $day['zz'][21]['o'] ? round($day['zz'][1]['o'] / $day['zz'][21]['o'], 2) : 0;
        $pressureRate['sz']['m'] = $day['sz'][21]['m'] ? round($day['sz'][1]['m'] / $day['sz'][21]['m'], 2) : 0;
        $pressureRate['sz']['i'] = $day['sz'][21]['i'] ? round($day['sz'][1]['i'] / $day['sz'][21]['i'], 2) : 0;
        $pressureRate['sz']['o'] = $day['sz'][21]['o'] ? round($day['sz'][1]['o'] / $day['sz'][21]['o'], 2) : 0;

        $dayStartArr = [
            'last' => [strtotime(date('Y-m-01 00:00:00', strtotime('-1 month'))), strtotime(date("Y-m-1 00:00:00"))],  // 上月
            'this' => [strtotime(date("Y-m-1 00:00:00")), strtotime(date('Y-m-01 00:00:00', strtotime('+1 month')))], // 本月
        ];
        $monthShipment = ['zz' => ['last' => ['m' => 0, 'i' => 0, 'o' => 0], 'this' => ['m' => 0, 'i' => 0, 'o' => 0]], 'sz' => ['last' => ['m' => 0, 'i' => 0, 'o' => 0], 'this' => ['m' => 0, 'i' => 0, 'o' => 0]]];
        foreach ($dayStartArr as $k => $dayRange) {
            $dayStart = $dayRange[0];
            $dayEnd = $dayRange[1];

            $where = [
                ['o.status', '=', 2],
                ['o.over_time', 'between', [$dayStart, $dayEnd]],
            ];
            if ($from) $where[] = ['o.is_auto_import', '=', $from];
            if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId) ? '=' : 'in', $factoryId];
            $list = db('order_size os')->join('order o', 'o.id = os.order_id')->join('sku s', 's.sku = o.sku ')->where($where)->field('os.daohuo_count,os.order_count,s.sku_type,s.cost')->select();

            foreach ($list as $sv) {
                $jianshu = $sv['daohuo_count'];
                // 加工费
                $moneyCost = $sv['order_count'] * $sv['cost'];

                if ($sv['sku_type'] == '针织') {
                    $monthShipment['zz'][$k]['m'] += $moneyCost;
                    $monthShipment['zz'][$k]['i'] += $jianshu;
                    $monthShipment['zz'][$k]['o'] += 1;
                } elseif ($sv['sku_type'] == '梭织') {
                    $monthShipment['sz'][$k]['m'] += $moneyCost;
                    $monthShipment['sz'][$k]['i'] += $jianshu;
                    $monthShipment['sz'][$k]['o'] += 1;
                }
            }
        }

        $result = [
            'days' => $days,                    // 日期列表
            'zz_orders' => $orders['zz'],        // 针织下单列表
            'zz_shipments' => $shipments['zz'],    // 针织出货列表
            'sz_orders' => $orders['sz'],        // 梭织下单列表
            'sz_shipments' => $shipments['sz'],    // 梭织出货列表
            // 针织
            'zz' => [
                'day7' => $day['zz'][7],            // 	7天日均
                'day14' => $day['zz'][14],        // 14天日均
                'day21' => $day['zz'][21],        // 21天日均
                'ing' => $day['zz'][1],            // 在途量
                'pressure' => $pressureRate['zz'],    // 压力系数
                'lastmonth_shipment' => $monthShipment['zz']['last'],    // 上月出货
                'thismonth_shipment' => $monthShipment['zz']['this'],    // 本月出货
            ],
            // 梭织
            'sz' => [
                'day7' => $day['sz'][7],        // 	7天日均
                'day14' => $day['sz'][14],        // 14天日均
                'day21' => $day['sz'][21],        // 21天日均
                'ing' => $day['sz'][1],            // 在途量
                'pressure' => $pressureRate['sz'],    // 压力系数
                'lastmonth_shipment' => $monthShipment['sz']['last'],    // 上月出货
                'thismonth_shipment' => $monthShipment['sz']['this'],    // 本月出货
            ],
        ];

        return $result;
    }

    /**
     * 入仓出货订单数据表格
     * @return array[]
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/7
     */
    public function getDeliverTable()
    {
        //1,参数处理
        $is_auto_import = $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $types = $this->request->param('types', '');
        $time_slot = $this->time_slot(true);
        if ($types == 'all') {
            $types = [];
            $types[] = "levite_last_month;{$time_slot['lastmonth']['begin']}~{$time_slot['lastmonth']['end']}";
            $types[] = "delivery_last_month;{$time_slot['lastmonth']['begin']}~{$time_slot['lastmonth']['end']}";
            $types[] = "levite_this_month;{$time_slot['thismonth']['begin']}~{$time_slot['thismonth']['end']}";
            $types[] = "delivery_this_month;{$time_slot['thismonth']['begin']}~{$time_slot['thismonth']['end']}";
            $types[] = "levite_yesterday;{$time_slot['yesterday']['begin']}~{$time_slot['yesterday']['end']}";
            $types[] = "delivery_yesterday;{$time_slot['yesterday']['begin']}~{$time_slot['yesterday']['end']}";
            $types[] = "order_yesterday;{$time_slot['yesterday']['begin']}~{$time_slot['yesterday']['end']}";
            $types[] = "order_today;{$time_slot['today']['begin']}~{$time_slot['today']['end']}";
            $types[] = "year_annual;{$time_slot['thisyear']['begin']}~{$time_slot['thisyear']['end']}";
            $types = implode(';;', $types);
        }
        $types = explode(';;', $types);
        $param = [];
        foreach ($types as $k => $v) {
            $temp = explode(';', $v);
            $temp2 = explode('~', $temp[1]);
            $time_slot_temp = $this->time_slot(false, $temp2[0], $temp2[1]);
            $param[$temp[0]] = [
                'startTime' => $time_slot_temp['auto']['begin'],
                'endTime' => $time_slot_temp['auto']['end'],
            ];
        }
        //2,数据查询
        $result = [];
        foreach ($param as $k => $v) {
            $sql_where = '';
            if ($is_auto_import > 0) {
                $sql_where .= " and o.is_auto_import={$is_auto_import} ";
            }
            if ($factoryId > 0) {
                $sql_where .= " and o.factory_id={$factoryId} ";
            }
            switch ($k) {
                case 'levite_yesterday':
                case 'levite_this_month':
                case 'levite_last_month'://#全部入仓--以发货子单为准
                    $sql = "SELECT   sum(o.order_price* IFNULL(od.store_count, 0)) as sum_fob_price
,sum(IFNULL(oext.cost_profit,0) * IFNULL(od.store_count, 0)) as sum_cost_price
,sum(IFNULL(od.store_count, 0)) as sum_count
,count(distinct od.order_id) as count_order_id
,count(distinct IF(o.is_new=1,od.order_id,null)) as count_order_id_is_new
,sum(IF(o.is_new=1,IFNULL(od.store_count, 0),0)) as sum_count_is_new
,sum(IF(s.sku_type='梭织',IFNULL(od.store_count, 0), 0)) as sum_count_shuozhi
,sum(IF(s.sku_type='针织',IFNULL(od.store_count, 0), 0)) as sum_count_zhenzhi
,count(distinct IF(s.sku_type='梭织',od.order_id,null)) as count_order_id_shuozhi
,count(distinct IF(s.sku_type='针织',od.order_id,null)) as count_order_id_zhenzhi
FROM wx_order_delivery od
LEFT JOIN wx_order_ext oext on (od.order_id=oext.order_id)
LEFT JOIN wx_order o on (o.id=od.order_id)
LEFT JOIN wx_sku s on (s.sku=o.sku)
where 
o.status in (0,1,2)  {$sql_where} 
and od.delivery_status=8
and od.store_time>={$v['startTime']} and od.store_time <= {$v['endTime']}
";
                    $temp = db()->query($sql);
                    $temp[0]['jian']['shuozhi'] = sprintf("%.1f", ($temp[0]['sum_count'] <= 0 ? 0 : $temp[0]['sum_count_shuozhi'] / $temp[0]['sum_count']) * 100);
                    $temp[0]['jian']['zhenzhi'] = sprintf("%.1f", ($temp[0]['sum_count'] <= 0 ? 0 : $temp[0]['sum_count_zhenzhi'] / $temp[0]['sum_count']) * 100);
                    $temp[0]['dan']['shuozhi'] = sprintf("%.1f", ($temp[0]['count_order_id'] <= 0 ? 0 : $temp[0]['count_order_id_shuozhi'] / $temp[0]['count_order_id']) * 100);
                    $temp[0]['dan']['zhenzhi'] = sprintf("%.1f", ($temp[0]['count_order_id'] <= 0 ? 0 : $temp[0]['count_order_id_zhenzhi'] / $temp[0]['count_order_id']) * 100);

                    $temp[0]['sum_fob_price'] = $this->numToWan($temp[0]['sum_fob_price']);
                    $temp[0]['sum_cost_price'] = $this->numToWan($temp[0]['sum_cost_price']);
                    $temp[0]['count_order_id'] = number_format($temp[0]['count_order_id'], 0);
                    $temp[0]['sum_count'] = number_format($temp[0]['sum_count'], 0);
                    $temp[0]['count_order_id_is_new'] = number_format($temp[0]['count_order_id_is_new'], 0);
                    $temp[0]['sum_count_is_new'] = number_format($temp[0]['sum_count_is_new'], 0);
                    $result[$k] = $temp[0];
                    break;
                case 'delivery_this_month':
                case 'delivery_yesterday':
                case 'delivery_last_month':
                    $sql = "SELECT   sum(o.order_price* IFNULL(od.real_shipment_count, 0)) as sum_fob_price
,sum(IFNULL(oext.cost_profit,0) * IFNULL(od.real_shipment_count, 0)) as sum_cost_price
,sum(IFNULL(od.real_shipment_count, 0)) as sum_count
,count(distinct od.order_id) as count_order_id
,count(distinct IF(o.is_new=1,od.order_id,null)) as count_order_id_is_new
,sum(IF(o.is_new=1,IFNULL(od.real_shipment_count, 0),0)) as sum_count_is_new
,sum(IF(s.sku_type='梭织',IFNULL(od.real_shipment_count, 0), 0)) as sum_count_shuozhi
,sum(IF(s.sku_type='针织',IFNULL(od.real_shipment_count, 0), 0)) as sum_count_zhenzhi
,count(distinct IF(s.sku_type='梭织',od.order_id,null)) as count_order_id_shuozhi
,count(distinct IF(s.sku_type='针织',od.order_id,null)) as count_order_id_zhenzhi
FROM wx_order_delivery od
LEFT JOIN wx_order_ext oext on (od.order_id=oext.order_id)
LEFT JOIN wx_order o on (o.id=od.order_id)
LEFT JOIN wx_sku s on (s.sku=o.sku)
where 
o.status in (0,1,2) {$sql_where} 
and od.delivery_status not in (6,7)
and od.delivery_time>={$v['startTime']} and od.delivery_time <= {$v['endTime']}
";
                    $temp = db()->query($sql);
                    $temp[0]['jian']['shuozhi'] = sprintf("%.1f", ($temp[0]['sum_count'] <= 0 ? 0 : $temp[0]['sum_count_shuozhi'] / $temp[0]['sum_count']) * 100);
                    $temp[0]['jian']['zhenzhi'] = sprintf("%.1f", ($temp[0]['sum_count'] <= 0 ? 0 : $temp[0]['sum_count_zhenzhi'] / $temp[0]['sum_count']) * 100);
                    $temp[0]['dan']['shuozhi'] = sprintf("%.1f", ($temp[0]['count_order_id'] <= 0 ? 0 : $temp[0]['count_order_id_shuozhi'] / $temp[0]['count_order_id']) * 100);
                    $temp[0]['dan']['zhenzhi'] = sprintf("%.1f", ($temp[0]['count_order_id'] <= 0 ? 0 : $temp[0]['count_order_id_zhenzhi'] / $temp[0]['count_order_id']) * 100);

                    $temp[0]['sum_fob_price'] = $this->numToWan($temp[0]['sum_fob_price']);
                    $temp[0]['sum_cost_price'] = $this->numToWan($temp[0]['sum_cost_price']);
                    $temp[0]['count_order_id'] = number_format($temp[0]['count_order_id'], 0);
                    $temp[0]['sum_count'] = number_format($temp[0]['sum_count'], 0);
                    $temp[0]['count_order_id_is_new'] = number_format($temp[0]['count_order_id_is_new'], 0);
                    $temp[0]['sum_count_is_new'] = number_format($temp[0]['sum_count_is_new'], 0);
                    $result[$k] = $temp[0];
                    break;
                case 'year_annual':
                    $sql = "SELECT   sum(o.order_price* IFNULL(od.real_shipment_count, 0)) as sum_fob_price
FROM wx_order_delivery od
LEFT JOIN wx_order_ext oext on (od.order_id=oext.order_id)
LEFT JOIN wx_order o on (o.id=od.order_id)
LEFT JOIN wx_sku s on (s.sku=o.sku)
where 
o.status in (0,1,2) {$sql_where} 
and od.delivery_status not in (6,7)
and od.delivery_time>={$v['startTime']} and od.delivery_time <= {$v['endTime']}
";
                    $temp = db()->query($sql);
                    $res_temp = [
                        'sum_fob_price' => $temp[0]['sum_fob_price'],
                        'year_target_money' => (new TargetService())->getTarget($factoryId, 5),
                    ];
                    $res_temp['finish_unit'] = sprintf('%.2f', $res_temp['year_target_money'] == 0 ? 0 : ($res_temp['sum_fob_price'] / $res_temp['year_target_money']) * 100);
                    $res_temp['sum_fob_price'] = $this->numToWan($res_temp['sum_fob_price']);
                    $res_temp['year_target_money'] = $this->numToWan($res_temp['year_target_money']);
                    $result[$k] = $res_temp;
                    break;
                case 'order_today':
                case 'order_yesterday':
                    $sql = "SELECT   sum(o.order_price* IFNULL(o.quantity, 0)) as sum_fob_price
,sum(IFNULL(oext.cost_profit,0) * IFNULL(o.quantity, 0)) as sum_cost_price
,sum(IFNULL(o.quantity, 0)) as sum_count
,count(o.id) as count_order_id
,count(distinct IF(o.is_new=1,o.id,null)) as count_order_id_is_new
,sum(IF(o.is_new=1,IFNULL(o.quantity, 0),0)) as sum_count_is_new
,sum(IF(s.sku_type='梭织',IFNULL(o.quantity, 0), 0)) as sum_count_shuozhi
,sum(IF(s.sku_type='针织',IFNULL(o.quantity, 0), 0)) as sum_count_zhenzhi
,count(distinct IF(s.sku_type='梭织',o.id,null)) as count_order_id_shuozhi
,count(distinct IF(s.sku_type='针织',o.id,null)) as count_order_id_zhenzhi
FROM wx_order o
LEFT JOIN wx_order_ext oext on (o.id=oext.order_id)
LEFT JOIN wx_sku s on (s.sku=o.sku)
where 
o.status in (0,1,2) {$sql_where} 
and o.create_time>={$v['startTime']} and o.create_time <= {$v['endTime']}";
                    $temp = db()->query($sql);
                    $temp[0]['jian']['shuozhi'] = sprintf("%.1f", ($temp[0]['sum_count'] <= 0 ? 0 : $temp[0]['sum_count_shuozhi'] / $temp[0]['sum_count']) * 100);
                    $temp[0]['jian']['zhenzhi'] = sprintf("%.1f", ($temp[0]['sum_count'] <= 0 ? 0 : $temp[0]['sum_count_zhenzhi'] / $temp[0]['sum_count']) * 100);
                    $temp[0]['dan']['shuozhi'] = sprintf("%.1f", ($temp[0]['count_order_id'] <= 0 ? 0 : $temp[0]['count_order_id_shuozhi'] / $temp[0]['count_order_id']) * 100);
                    $temp[0]['dan']['zhenzhi'] = sprintf("%.1f", ($temp[0]['count_order_id'] <= 0 ? 0 : $temp[0]['count_order_id_zhenzhi'] / $temp[0]['count_order_id']) * 100);

                    $temp[0]['sum_fob_price'] = $this->numToWan($temp[0]['sum_fob_price']);
                    $temp[0]['sum_cost_price'] = $this->numToWan($temp[0]['sum_cost_price']);
                    $temp[0]['count_order_id'] = number_format($temp[0]['count_order_id'], 0);
                    $temp[0]['sum_count'] = number_format($temp[0]['sum_count'], 0);
                    $temp[0]['count_order_id_is_new'] = number_format($temp[0]['count_order_id_is_new'], 0);
                    $temp[0]['sum_count_is_new'] = number_format($temp[0]['sum_count_is_new'], 0);
                    $result[$k] = $temp[0];
                    break;
            }
        }
        return json(['code' => 1, 'msg' => '', 'data' => $result]);
    }

    public function numToWan($num)
    {
        return sprintf("%.2f万", $num / 10000);
    }

    /**
     * 入仓出货订单数据详情
     * @return string
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/8
     */
    public function getDeliverTableDetail()
    {
        $is_auto_import = $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $types = $this->request->param('types', '');
        //2,数据查询
        if ($this->request->isAjax()) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $time_slot = $this->time_slot(true);
            switch ($types) {
                case 'levite_last_month':
                    $types = [];
                    $types[] = "levite_last_month;{$time_slot['lastmonth']['begin']}~{$time_slot['lastmonth']['end']}";
                    $types = implode(';;', $types);
                    break;
                case 'delivery_last_month':
                    $types = [];
                    $types[] = "delivery_last_month;{$time_slot['lastmonth']['begin']}~{$time_slot['lastmonth']['end']}";
                    $types = implode(';;', $types);
                    break;
                case 'levite_this_month':
                    $types = [];
                    $types[] = "levite_this_month;{$time_slot['thismonth']['begin']}~{$time_slot['thismonth']['end']}";
                    $types = implode(';;', $types);
                    break;
                case 'delivery_this_month':
                    $types = [];
                    $types[] = "delivery_this_month;{$time_slot['thismonth']['begin']}~{$time_slot['thismonth']['end']}";
                    $types = implode(';;', $types);
                    break;
                case 'levite_yesterday':
                    $types = [];
                    $types[] = "levite_yesterday;{$time_slot['yesterday']['begin']}~{$time_slot['yesterday']['end']}";
                    $types = implode(';;', $types);
                    break;
                case 'delivery_yesterday':
                    $types = [];
                    $types[] = "delivery_yesterday;{$time_slot['yesterday']['begin']}~{$time_slot['yesterday']['end']}";
                    $types = implode(';;', $types);
                    break;
                case 'order_yesterday':
                    $types = [];
                    $types[] = "order_yesterday;{$time_slot['yesterday']['begin']}~{$time_slot['yesterday']['end']}";
                    $types = implode(';;', $types);
                    break;
                case 'order_today':
                    $types = [];
                    $types[] = "order_today;{$time_slot['today']['begin']}~{$time_slot['today']['end']}";
                    $types = implode(';;', $types);
                    break;
            }
            $types = explode(';;', $types);
            $param = [];
            foreach ($types as $k => $v) {
                $temp = explode(';', $v);
                $temp2 = explode('~', $temp[1]);
                $time_slot_temp = $this->time_slot(false, $temp2[0], $temp2[1]);
                $param[$temp[0]] = [
                    'startTime' => $time_slot_temp['auto']['begin'],
                    'endTime' => $time_slot_temp['auto']['end'],
                ];
            }
            foreach ($param as $k => $v) {
                $whereRaw = '1=1 ';
                if ($is_auto_import > 0) {
                    $whereRaw .= " and o.is_auto_import={$is_auto_import} ";
                }
                if ($factoryId > 0) {
                    $whereRaw .= " and o.factory_id={$factoryId} ";
                }
                switch ($k) {
                    case 'levite_yesterday':
                    case 'levite_this_month':
                    case 'levite_last_month':
                        $whereRaw .= " and o.status in (0,1,2) 
and od.delivery_status=8
and od.store_time>={$v['startTime']} and od.store_time <= {$v['endTime']} ";
                        $list = db('order_delivery od ')
                            ->field('o.id,o.client_ordernum,o.order_price,oext.cost_profit,sum(od.store_count) as sum_count,od.store_time as create_time
                            ,o.status as order_status,o.caigou_status,o.caichuang_status,o.chejian_status,o.tail_status,o.real_shipment_status
                            ,ft.name as ft_name
                            ')
                            ->join('order o', 'o.id=od.order_id', 'left')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->whereRaw($whereRaw)
                            ->page($page)
                            ->limit($limit)
                            ->order("od.store_time desc")
                            ->group('od.order_id')
                            ->select();
                        foreach ($list as $k2 => $v2) {
                            $list[$k2]['create_time'] = date('Y-m-d H:i:s', $list[$k2]['create_time']);
                            $list[$k2]['status_txt'] = $this->_get_order_status_txt($v2);
                        }
                        $data['count'] = db('order_delivery od ')
                            ->join('order o', 'o.id=od.order_id', 'left')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->whereRaw($whereRaw)
                            ->group('od.order_id')
                            ->count();
                        $data['data'] = $list;
                        $data['code'] = 0;
                        $data['msg'] = '';
                        return json($data);
                        break;
                    case 'delivery_this_month':
                    case 'delivery_yesterday':
                    case 'delivery_last_month':
                        $whereRaw .= " and o.status in (0,1,2) 
and od.delivery_status not in (6,7)
and od.delivery_time>={$v['startTime']} and od.delivery_time <= {$v['endTime']}";
                        $list = db('order_delivery od ')
                            ->field('o.id,o.client_ordernum,o.order_price,oext.cost_profit,sum(od.real_shipment_count) as sum_count,od.delivery_time as create_time
                            ,o.status as order_status,o.caigou_status,o.caichuang_status,o.chejian_status,o.tail_status,o.real_shipment_status
                            ,ft.name as ft_name
                            ')
                            ->join('order o', 'o.id=od.order_id', 'left')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->whereRaw($whereRaw)
                            ->page($page)
                            ->limit($limit)
                            ->order("od.delivery_time  desc")
                            ->group('od.order_id')
                            ->select();
                        foreach ($list as $k2 => $v2) {
                            $list[$k2]['create_time'] = date('Y-m-d H:i:s', $list[$k2]['create_time']);
                            $list[$k2]['status_txt'] = $this->_get_order_status_txt($v2);
                        }
                        $data['count'] = db('order_delivery od ')
                            ->join('order o', 'o.id=od.order_id', 'left')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->whereRaw($whereRaw)
                            ->group('od.order_id')
                            ->count();
                        $data['data'] = $list;
                        $data['code'] = 0;
                        $data['msg'] = '';
                        return json($data);
                        break;
                    case 'order_yesterday':
                    case 'order_today':
                        $whereRaw .= " and o.status in (0,1,2) 
and o.create_time>={$v['startTime']} and o.create_time <= {$v['endTime']} ";
                        $list = db('order o')
                            ->field('o.id,o.client_ordernum,o.order_price,oext.cost_profit,o.quantity as sum_count,o.create_time
                            ,o.status as order_status,o.caigou_status,o.caichuang_status,o.chejian_status,o.tail_status,o.real_shipment_status
                            ,ft.name as ft_name
                            ')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->whereRaw($whereRaw)
                            ->page($page)
                            ->limit($limit)
                            ->order("o.over_time desc")
                            ->select();
                        foreach ($list as $k2 => $v2) {
                            $list[$k2]['create_time'] = date('Y-m-d H:i:s', $list[$k2]['create_time']);
                            $list[$k2]['status_txt'] = $this->_get_order_status_txt($v2);
                        }
                        $data['count'] = db('order o')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->whereRaw($whereRaw)
                            ->count();
                        $data['data'] = $list;
                        $data['code'] = 0;
                        $data['msg'] = '';
                        return json($data);
                        break;
                }
            }
        }
        $this->assign('thisFrom', $from);
        $this->assign('thisFactoryId', $factoryId);
        $this->assign('types', $types);
        return $this->fetch('get_deliverTable_detail');
    }

    //获取订单状态说明
    private function _get_order_status_txt_2($v)
    {
        if ($v['order_status'] == 99 || $v['order_status'] == 999) {
            return '已作废';
        }
        if ($v['caigou_status'] == 0) {
            return '未采购';
        }
        if ($v['caichuang_status'] == 0) {
            return '已采购';
        }
        if ($v['chejian_status'] == 0) {
            return '已裁床';
        }
        if ($v['tail_status'] == 0) {
            return '已车缝';
        }
        if ($v['real_shipment_status'] == 0) {
            return '已后整';
        }
        if ($v['order_status'] == 1) {
            return '已出货';
        }
        if ($v['order_status'] == 2) {
            return '已完成';
        }
        return '未知';
    }

    //获取订单状态说明
    private function _get_order_status_txt($v)
    {
        $v['status'] = $v['order_status'];

        if ($v['status'] == 99) {
            return '已废弃';
        }
        if ($v['status'] == 99) {
            return 'MES废除';
        }
        if ($v['caigou_status'] == 0) {
            return '未采购';
        }
        if ($v['caigou_status'] == 1 && $v['caichuang_status'] == 0) {
            return '已采购';
        }
        if ($v['caichuang_status'] == 1 && $v['chejian_status'] == 0) {
            return '已裁床';
        }
        if ($v['chejian_status'] == 1 && $v['tail_status'] == 0) {
            return '已车缝';
        }
        if ($v['tail_status'] == 1 && $v['real_shipment_status'] == 0) {
            return '已后整';
        }
        if ($v['real_shipment_status'] == 1 && $v['status'] == 1) {
            return '已出货';
        }
        if ($v['status'] == 2) {
            return '已完成';
        }
        return '新单未处理';
    }

    /**
     * 上月下单出货情况
     * @return string|\think\response\Json
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/8
     */
    public function chart_order_delivery()
    {
        if ($this->request->isAjax()) {
            $param = [
                'unit' => $this->request->param('unit', 'day'),
                'create_date_range' => $this->request->param('create_date_range', date("Y-m-01") . '~' . date("Y-m-d")),
                'factory_id' => $this->request->param('factory_id/d', 0),
                'is_auto_import' => $this->request->param('from/d', 0),
                'date_type' => $this->request->param('date_type/s', 'last_month'),
                'type' => $this->request->param('type/s', '件数'),
                'sku_type' => $this->request->param('sku_type/s', '全部'),
            ];
            list($param['start_time'], $param['end_time']) = array_map('strtotime', explode('~', $param['create_date_range']));
            list($param['start'], $param['end']) = array_map('trim', explode('~', $param['create_date_range']));
            $param['end_time'] += 24 * 3600 - 1;
            $highcharts_data = (new Daily)->chart_order_delivery($param);
            return json(['code' => 0, 'msg' => '', 'data' => $highcharts_data]);
        }
    }

    /**
     * 在途产能--信息查询
     * #件数： wx_order_size   order_count  shicai_count  jiaohuo_count 这三个最新的数为件数
     * #如以发货，就用最新件数 - 已发货数 = 最终件数
     * #fob价=最终件数*o.order_price
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/10
     */
    public function getDeliverNotFinish()
    {
        $is_auto_import = $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $whereRaw = '1=1 ';
        if ($is_auto_import > 0) {
            $whereRaw .= " and o.is_auto_import={$is_auto_import} ";
        }
        if ($factoryId > 0) {
            $whereRaw .= " and o.factory_id={$factoryId} ";
        }
        $sql = "SELECT   
o.id as order_id,o.client_ordernum,o.order_price
,sku.sku_type
,sum(os.order_count) as sum_order_count
,sum(os.shicai_count) as sum_shicai_count
,sum(os.jiaohuo_count) as sum_jiaohuo_count
,sum(od.delivery_count) as sum_delivery_count
FROM wx_order o
LEFT JOIN wx_order_ext oext on (o.id=oext.order_id)
LEFT JOIN wx_sku sku on (sku.sku=o.sku)
LEFT JOIN wx_order_size os on (o.id=os.order_id)
LEFT JOIN wx_order_delivery od on (o.id=od.order_id)
where {$whereRaw}
and o.status in (0,1) and o.tail_status=0
GROUP BY o.id";
        $list = db()->query($sql);
        $result = [
            'sum_fob_price' => 0,
            'sum_count' => 0,
            'count_order_id' => 0,
            'sum_fob_price_shuozhi' => 0,
            'sum_count_shuozhi' => 0,
            'count_order_id_shuozhi' => 0,
            'sum_fob_price_zhenzhi' => 0,
            'sum_count_zhenzhi' => 0,
            'count_order_id_zhenzhi' => 0,
        ];
        foreach ($list as $k => $v) {
            $a_count = floatval($v['sum_jiaohuo_count']) > 0 ? floatval($v['sum_jiaohuo_count']) :
                $v['sum_shicai_count'] > 0 ? $v['sum_shicai_count'] :
                    $v['sum_order_count'] > 0 ? $v['sum_order_count'] : 0;
            $end_count = $a_count - floatval($v['sum_delivery_count']);
            $result['sum_fob_price'] += ($end_count * $v['order_price']);
            $result['sum_count'] += $end_count;
            $result['count_order_id']++;
            if (trim($v['sku_type']) == '梭织') {
                $result['sum_fob_price_shuozhi'] += ($end_count * $v['order_price']);
                $result['sum_count_shuozhi'] += $end_count;
                $result['count_order_id_shuozhi']++;
            }
            if (trim($v['sku_type']) == '针织') {
                $result['sum_fob_price_zhenzhi'] += ($end_count * $v['order_price']);
                $result['sum_count_zhenzhi'] += $end_count;
                $result['count_order_id_zhenzhi']++;
            }
        }
        $result['sum_fob_price'] = sprintf("%.2f", $result['sum_fob_price']);
        $result['sum_fob_price_shuozhi'] = sprintf("%.2f", $result['sum_fob_price_shuozhi']);
        $result['sum_fob_price_zhenzhi'] = sprintf("%.2f", $result['sum_fob_price_zhenzhi']);
        return json(['code' => 1, 'msg' => '', 'data' => $result]);
    }

    /**
     * 在途产能--详情信息
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/10
     */
    public function getDeliverNotFinishDetail()
    {
        $is_auto_import = $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $types = $this->request->param('types', '');
        $sku_type = $this->request->param('sku_type/s', '');
        //2,数据查询
        if ($this->request->isAjax()) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            switch ($types) {
                case 'days_avg_7':
                    $types = "days_avg_7;null";
                    break;
                case 'days_avg_14':
                    $types = "days_avg_14;null";
                    break;
                case 'days_avg_21':
                    $types = "days_avg_21;null";
                    break;
                case 'all':
                    $types = "all;null";
                    break;
            }
            $types = explode(';;', $types);
            $param = [];
            foreach ($types as $k => $v) {
                $temp = explode(';', $v);
                $param[$temp[0]] = [];
            }
            foreach ($param as $k => $v) {
                $whereRaw = '1=1 ';
                if ($is_auto_import > 0) {
                    $whereRaw .= " and o.is_auto_import={$is_auto_import} ";
                }
                if ($factoryId > 0) {
                    $whereRaw .= " and o.factory_id={$factoryId} ";
                }
                $begin = 0;
                $end = 0;
                $time_list = [];
                $time_list['7']['begin'] = mktime(0, 0, 0, date('m'), date('d') - 7, date('Y'));
                $time_list['7']['end'] = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
                $time_list['14']['begin'] = mktime(0, 0, 0, date('m'), date('d') - 14, date('Y'));
                $time_list['14']['end'] = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
                $time_list['21']['begin'] = mktime(0, 0, 0, date('m'), date('d') - 21, date('Y'));
                $time_list['21']['end'] = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;

                switch ($k) {
                    case 'days_avg_7':
                        $begin == 0 && $begin = $time_list['7']['begin'];
                        $end == 0 && $end = $time_list['7']['end'];
                    case 'days_avg_14':
                        $begin == 0 && $begin = $time_list['14']['begin'];
                        $end == 0 && $end = $time_list['14']['end'];
                    case 'days_avg_21':
                        $begin == 0 && $begin = $time_list['21']['begin'];
                        $end == 0 && $end = $time_list['21']['end'];
                        $sku_type == 'zhenzhi' && $whereRaw .= " and s.sku_type='针织' ";
                        $sku_type == 'shuozhi' && $whereRaw .= " and s.sku_type='梭织' ";
                        $whereRaw .= " and o.status in (0,1,2) and o.client_status<>99
and od.delivery_status not in (6,7) 
and od.delivery_time BETWEEN {$begin} and {$end}
";
                        $list = db('order_delivery od ')
                            ->field('od.id,o.client_ordernum,o.order_price,oext.cost_profit,o.quantity,o.create_time
                            ,o.status as order_status,o.caigou_status,o.caichuang_status,o.chejian_status,o.tail_status,o.real_shipment_status
                            ,o.is_new
                            ,s.sku_type
                            ,ft.name as ft_name
                            ,od.delivery_time,od.delivery_number,od.delivery_status,od.delivery_count
                            ')
                            ->join('order o', 'o.id=od.order_id', 'left')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->join('sku s', 'o.sku=s.sku', 'left')
                            ->whereRaw($whereRaw)
                            ->page($page)
                            ->limit($limit)
                            ->order("od.id desc")
                            ->select();
                        $result = [
                            'all' => [
                                'jianshu' => 0,
                                'money' => 0,
                                'num' => 0,
                                'num_is_new' => 0,
                            ],
                            'shuozhi' => [
                                'jianshu' => 0,
                                'money' => 0,
                                'num' => 0,
                                'num_is_new' => 0,
                            ],
                            'zhenzhi' => [
                                'jianshu' => 0,
                                'money' => 0,
                                'num' => 0,
                                'num_is_new' => 0,
                            ],
                        ];
                        $delivery_status = config('mimo.delivery_status');
                        foreach ($list as $k2 => $v2) {
                            $list[$k2]['create_time'] = date('Y-m-d H:i:s', $list[$k2]['delivery_time']);
                            $list[$k2]['status_txt'] = $delivery_status[$v2['delivery_status']];
                            $list[$k2]['is_new_txt'] = $v2['is_new'] == 1 ? '首单' : '返单';
                            $list[$k2]['end_count'] = $v2['end_count'] = $end_count = $v2['delivery_count'];
                            $list[$k2]['price_fob'] = sprintf("%.2f", $list[$k2]['end_count'] * $v2['order_price']);
                            $list[$k2]['price_cost_profit'] = sprintf("%.2f", $list[$k2]['end_count'] * $v2['cost_profit']);

                            $result['all']['money'] += ($end_count * $v2['cost_profit']);
                            $result['all']['jianshu'] += $end_count;
                            $result['all']['num']++;
                            $v2['is_new'] == 1 && $result['all']['num_is_new']++;
                            if (trim($v2['sku_type']) == '梭织') {
                                $result['shuozhi']['money'] += ($end_count * $v2['cost_profit']);
                                $result['shuozhi']['jianshu'] += $end_count;
                                $result['shuozhi']['num']++;
                                $v2['is_new'] == 1 && $result['shuozhi']['num_is_new']++;
                            }
                            if (trim($v2['sku_type']) == '针织') {
                                $result['zhenzhi']['money'] += ($end_count * $v2['cost_profit']);
                                $result['zhenzhi']['jianshu'] += $end_count;
                                $result['zhenzhi']['num']++;
                                $v2['is_new'] == 1 && $result['zhenzhi']['num_is_new']++;
                            }
                        }
                        $data['count'] = db('order_delivery od ')
                            ->join('order o', 'o.id=od.order_id', 'left')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->join('sku s', 'o.sku=s.sku', 'left')
                            ->whereRaw($whereRaw)
                            ->count();
                        $data['result'] = $result;
                        $data['data'] = $list;
                        $data['code'] = 0;
                        $data['msg'] = '';
                        return json($data);
                        break;
                    case 'all':
                        $sku_type == 'zhenzhi' && $whereRaw .= " and s.sku_type='针织' ";
                        $sku_type == 'shuozhi' && $whereRaw .= " and s.sku_type='梭织' ";
                        $whereRaw .= " and o.status in (0,1) and o.client_status<>99
";
                        $list = db('order o')
                            ->field('o.id,o.client_ordernum,o.order_price,oext.cost_profit,o.quantity,o.create_time
                            ,o.status as order_status,o.caigou_status,o.caichuang_status,o.chejian_status,o.tail_status,o.real_shipment_status
                            ,o.is_new
                            ,s.sku_type
                            ,ft.name as ft_name
                            ,sum(os.order_count) as sum_order_count
,sum(os.shicai_count) as sum_shicai_count
,sum(os.jiaohuo_count) as sum_jiaohuo_count
                            ')
//                            ->join('order_delivery od ', 'o.id=od.order_id and  od.delivery_status not in (6,7) ', 'left')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->join('order_size os', 'o.id=os.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->join('sku s', 'o.sku=s.sku', 'left')
                            ->whereRaw($whereRaw)
                            ->page($page)
                            ->limit($limit)
                            ->order("o.id desc")
                            ->group('o.id')
                            ->select();
                        $list2 = db('order o')
                            ->field('o.id
,sum(od.delivery_count) as sum_delivery_count
                            ')
                            ->join('order_delivery od ', 'o.id=od.order_id and  od.delivery_status not in (6,7) ', 'left')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
//                            ->join('order_size os', 'o.id=os.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->join('sku s', 'o.sku=s.sku', 'left')
                            ->whereRaw($whereRaw)
                            ->page($page)
                            ->limit($limit)
                            ->order("o.id desc")
                            ->group('o.id')
                            ->select();
                        foreach ($list as $k => $v) {
                            foreach ($list2 as $k2 => $v2) {
                                if ($v['id'] == $v2['id']) {
                                    $list[$k]['sum_delivery_count'] = $v2['sum_delivery_count'];
                                }
                            }
                        }
                        $result = [
                            'all' => [
                                'jianshu' => 0,
                                'money' => 0,
                                'num' => 0,
                                'num_is_new' => 0,
                            ],
                            'shuozhi' => [
                                'jianshu' => 0,
                                'money' => 0,
                                'num' => 0,
                                'num_is_new' => 0,
                            ],
                            'zhenzhi' => [
                                'jianshu' => 0,
                                'money' => 0,
                                'num' => 0,
                                'num_is_new' => 0,
                            ],
                        ];
                        foreach ($list as $k2 => $v2) {
                            $list[$k2]['create_time'] = date('Y-m-d H:i:s', $list[$k2]['create_time']);
                            $list[$k2]['status_txt'] = $this->_get_order_status_txt($v2);
                            $list[$k2]['is_new_txt'] = $v2['is_new'] == 1 ? '首单' : '返单';
                            $a_count = floatval($v2['sum_jiaohuo_count']) > 0 ? floatval($v2['sum_jiaohuo_count']) :
                                $v2['sum_shicai_count'] > 0 ? $v2['sum_shicai_count'] :
                                    $v2['sum_order_count'] > 0 ? $v2['sum_order_count'] : 0;
                            $end_count = $a_count - floatval($v2['sum_delivery_count']);
                            $list[$k2]['end_count'] = $end_count;
                            $list[$k2]['price_fob'] = sprintf("%.2f", $list[$k2]['end_count'] * $v2['order_price']);
                            $list[$k2]['price_cost_profit'] = sprintf("%.2f", $list[$k2]['end_count'] * $v2['cost_profit']);

                            $result['all']['money'] += ($end_count * $v2['cost_profit']);
                            $result['all']['jianshu'] += $end_count;
                            $result['all']['num']++;
                            $v2['is_new'] == 1 && $result['all']['num_is_new']++;
                            if (trim($v2['sku_type']) == '梭织') {
                                $result['shuozhi']['money'] += ($end_count * $v2['cost_profit']);
                                $result['shuozhi']['jianshu'] += $end_count;
                                $result['shuozhi']['num']++;
                                $v2['is_new'] == 1 && $result['shuozhi']['num_is_new']++;
                            }
                            if (trim($v2['sku_type']) == '针织') {
                                $result['zhenzhi']['money'] += ($end_count * $v2['cost_profit']);
                                $result['zhenzhi']['jianshu'] += $end_count;
                                $result['zhenzhi']['num']++;
                                $v2['is_new'] == 1 && $result['zhenzhi']['num_is_new']++;
                            }
                        }
                        $data['count'] = db('order o')
                            ->join('order_delivery od ', 'o.id=od.order_id', 'left')
                            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
                            ->join('order_size os', 'o.id=os.order_id', 'left')
                            ->join('factory ft', 'ft.id=o.factory_id', 'left')
                            ->join('sku s', 'o.sku=s.sku', 'left')
                            ->whereRaw($whereRaw)
                            ->group('o.id')
                            ->count();
                        $data['result'] = $result;
                        $data['data'] = $list;
                        $data['code'] = 0;
                        $data['msg'] = '';
                        return json($data);
                        break;
                }
            }
        }
        $this->assign('thisFrom', $from);
        $this->assign('thisFactoryId', $factoryId);
        $this->assign('types', $types);
        $this->assign('sku_type', $sku_type);
        return $this->fetch('get_deliver_not_finish_detail');
    }

    /**
     * 时间段（本日，昨日，本周，上周，本月，上月）
     * @param bool $date_flag false--以秒为单的时间戳  true日期
     * @param string $auto_start 2022-01-01
     * @param string $auto_end 2022-01-10
     * @param int $type 扩展使用--作用auto的开始与结束时间
     * @return array
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/16
     */
    public function time_slot($date_flag = false, $auto_start = '', $auto_end = '', $type = 0)
    {
        $time = [];
        $time['today']['begin'] = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $time['today']['end'] = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        $time['yesterday']['begin'] = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $time['yesterday']['end'] = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        $time['thisweek']['begin'] = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"));
        $time['thisweek']['end'] = mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y"));
        $time['lastweek']['begin'] = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y'));
        $time['lastweek']['end'] = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y'));
        $time['thismonth']['begin'] = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $time['thismonth']['end'] = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        $time['lastmonth']['begin'] = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));
        $time['lastmonth']['end'] = mktime(23, 59, 59, date("m"), 0, date("Y"));
        $time['thisyear']['begin'] = mktime(0, 0, 0, 1, 1, date("Y"));
        $time['thisyear']['end'] = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        switch ($type) {
            case 0:
            default:
                $time['auto']['begin'] = strtotime(date('Y-m-d', strtotime($auto_start)));
                $time['auto']['end'] = strtotime(date('Y-m-d 23:59:59', strtotime($auto_end)));
                break;
        }
        if ($date_flag == true) {
            foreach ($time as $k => $v) {
                $time[$k]['begin'] = date('Y-m-d H:i:s', $v['begin']);
                $time[$k]['end'] = date('Y-m-d H:i:s', $v['end']);
            }
        }
        return $time;
    }

    /**
     * 在途产能--信息查询
     * #件数： wx_order_size   order_count  shicai_count  jiaohuo_count 这三个最新的数为件数
     * #如以发货，就用最新件数 - 已发货数 = 最终件数
     * #fob价=最终件数*o.order_price
     * #时间--取最新的时间：wx_order表 订购 create_time  裁床 caichuang_status=1 caichuang_over_time 车间 chejian_status=1 chejian_over_time
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/10
     */
    public function getDeliverNotFinishAll()
    {
        $is_auto_import = $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $result = $this->getDeliverNotFinishAll_res($is_auto_import, $factoryId);
        //数据显示处理
        $result['all']['all']['jianshu'] = $this->numToWan($result['all']['all']['jianshu']);
        $result['all']['all']['money'] = $this->numToWan($result['all']['all']['money']);
        $result['all']['zhenzhi']['jianshu'] = $this->numToWan($result['all']['zhenzhi']['jianshu']);
        $result['all']['zhenzhi']['money'] = $this->numToWan($result['all']['zhenzhi']['money']);
        $result['all']['shuozhi']['jianshu'] = $this->numToWan($result['all']['shuozhi']['jianshu']);
        $result['all']['shuozhi']['money'] = $this->numToWan($result['all']['shuozhi']['money']);

        $result['days_avg_7']['avg']['all']['jianshu'] = $this->numToWan($result['days_avg_7']['avg']['all']['jianshu']);
        $result['days_avg_7']['avg']['all']['money'] = $this->numToWan($result['days_avg_7']['avg']['all']['money']);
        $result['days_avg_7']['avg']['zhenzhi']['jianshu'] = $this->numToWan($result['days_avg_7']['avg']['zhenzhi']['jianshu']);
        $result['days_avg_7']['avg']['zhenzhi']['money'] = $this->numToWan($result['days_avg_7']['avg']['zhenzhi']['money']);
        $result['days_avg_7']['avg']['shuozhi']['jianshu'] = $this->numToWan($result['days_avg_7']['avg']['shuozhi']['jianshu']);
        $result['days_avg_7']['avg']['shuozhi']['money'] = $this->numToWan($result['days_avg_7']['avg']['shuozhi']['money']);

        $result['days_avg_14']['avg']['all']['jianshu'] = $this->numToWan($result['days_avg_14']['avg']['all']['jianshu']);
        $result['days_avg_14']['avg']['all']['money'] = $this->numToWan($result['days_avg_14']['avg']['all']['money']);
        $result['days_avg_14']['avg']['zhenzhi']['jianshu'] = $this->numToWan($result['days_avg_14']['avg']['zhenzhi']['jianshu']);
        $result['days_avg_14']['avg']['zhenzhi']['money'] = $this->numToWan($result['days_avg_14']['avg']['zhenzhi']['money']);
        $result['days_avg_14']['avg']['shuozhi']['jianshu'] = $this->numToWan($result['days_avg_14']['avg']['shuozhi']['jianshu']);
        $result['days_avg_14']['avg']['shuozhi']['money'] = $this->numToWan($result['days_avg_14']['avg']['shuozhi']['money']);

        $result['days_avg_21']['avg']['all']['jianshu'] = $this->numToWan($result['days_avg_21']['avg']['all']['jianshu']);
        $result['days_avg_21']['avg']['all']['money'] = $this->numToWan($result['days_avg_21']['avg']['all']['money']);
        $result['days_avg_21']['avg']['zhenzhi']['jianshu'] = $this->numToWan($result['days_avg_21']['avg']['zhenzhi']['jianshu']);
        $result['days_avg_21']['avg']['zhenzhi']['money'] = $this->numToWan($result['days_avg_21']['avg']['zhenzhi']['money']);
        $result['days_avg_21']['avg']['shuozhi']['jianshu'] = $this->numToWan($result['days_avg_21']['avg']['shuozhi']['jianshu']);
        $result['days_avg_21']['avg']['shuozhi']['money'] = $this->numToWan($result['days_avg_21']['avg']['shuozhi']['money']);

        return json(['code' => 1, 'msg' => '', 'data' => $result]);
    }

    private function _getDeliverNotFinishAll_min($type = 'all', $whereRaw, $begin = 0, $end = 0, $days = 0)
    {
        switch ($type) {
            case 'avg':
                $result = [];
                $sql_ary = [
                    'all' => '',
                    'shuozhi' => " and sku.sku_type='梭织' ",
                    'zhenzhi' => " and sku.sku_type='针织' "
                ];
                foreach ($sql_ary as $k => $v) {
                    $sql = "SELECT   
sum(IFNULL(oext.cost_profit,0) * IFNULL(od.delivery_count, 0)) as money
,sum(IFNULL(od.delivery_count, 0)) as jianshu
,count(distinct od.order_id) as num
FROM wx_order_delivery od
LEFT JOIN wx_order_ext oext on (od.order_id=oext.order_id)
LEFT JOIN wx_order o on (o.id=od.order_id)
LEFT JOIN wx_sku sku on (sku.sku=o.sku)
where 
{$whereRaw} and o.status in (0,1,2) and o.client_status<>99  {$v}
and od.delivery_status not in (6,7) 
and od.delivery_time BETWEEN {$begin} and {$end} ";
                    $info = db()->query($sql);
                    $result[$k] = $info[0];
                }
                $avg = [];
                foreach ($result as $k => $v) {
                    foreach ($v as $k2 => $v2) {
                        $avg[$k][$k2] = round($v2 / $days, 2);
                    }
                }
                $result['avg'] = $avg;
                return $result;
                break;
            case 'all':
                $sql = "SELECT   
o.id as order_id,o.client_ordernum,o.order_price,o.is_new
,IFNULL(oext.cost_profit,0) as cost_profit
,sku.sku_type
,sum(os.order_count) as sum_order_count
,sum(os.shicai_count) as sum_shicai_count
,sum(os.jiaohuo_count) as sum_jiaohuo_count
FROM wx_order o
LEFT JOIN wx_order_ext oext on (o.id=oext.order_id)
LEFT JOIN wx_sku sku on (sku.sku=o.sku)
LEFT JOIN wx_order_size os on (o.id=os.order_id)
where {$whereRaw}
and o.status in (0,1) and o.client_status<>99
GROUP BY o.id";
                $list = db()->query($sql);
                $sql = "SELECT   
o.id as order_id,o.client_ordernum,o.order_price,o.is_new
,IFNULL(oext.cost_profit,0) as cost_profit
,sku.sku_type
,sum(od.delivery_count) as sum_delivery_count
FROM wx_order o
LEFT JOIN wx_order_ext oext on (o.id=oext.order_id)
LEFT JOIN wx_sku sku on (sku.sku=o.sku)
LEFT JOIN wx_order_delivery od on (o.id=od.order_id and  od.delivery_status not in (6,7) )
where {$whereRaw}
and o.status in (0,1) and o.client_status<>99
GROUP BY o.id";
                $list2 = db()->query($sql);
                foreach ($list as $k => $v) {
                    foreach ($list2 as $k2 => $v2) {
                        if ($v['order_id'] == $v2['order_id']) {
                            $list[$k]['sum_delivery_count'] = $v2['sum_delivery_count'];
                        }
                    }
                }
                $result = [
                    'all' => [
                        'jianshu' => 0,
                        'money' => 0,
                        'num' => 0,
                        'num_is_new' => 0,
                    ],
                    'shuozhi' => [
                        'jianshu' => 0,
                        'money' => 0,
                        'num' => 0,
                        'num_is_new' => 0,
                    ],
                    'zhenzhi' => [
                        'jianshu' => 0,
                        'money' => 0,
                        'num' => 0,
                        'num_is_new' => 0,
                    ],
                ];
                foreach ($list as $k => $v) {
                    $a_count = floatval($v['sum_jiaohuo_count']) > 0 ? floatval($v['sum_jiaohuo_count']) :
                        $v['sum_shicai_count'] > 0 ? $v['sum_shicai_count'] :
                            $v['sum_order_count'] > 0 ? $v['sum_order_count'] : 0;
                    $end_count = $a_count - floatval($v['sum_delivery_count']);
                    $result['all']['money'] += ($end_count * $v['cost_profit']);
                    $result['all']['jianshu'] += $end_count;
                    $result['all']['num']++;
                    $v['is_new'] == 1 && $result['all']['num_is_new']++;
                    if (trim($v['sku_type']) == '梭织') {
                        $result['shuozhi']['money'] += ($end_count * $v['cost_profit']);
                        $result['shuozhi']['jianshu'] += $end_count;
                        $result['shuozhi']['num']++;
                        $v['is_new'] == 1 && $result['shuozhi']['num_is_new']++;
                    }
                    if (trim($v['sku_type']) == '针织') {
                        $result['zhenzhi']['money'] += ($end_count * $v['cost_profit']);
                        $result['zhenzhi']['jianshu'] += $end_count;
                        $result['zhenzhi']['num']++;
                        $v['is_new'] == 1 && $result['zhenzhi']['num_is_new']++;
                    }
                }
                return $result;
                break;
        }
    }

    private function getDeliverNotFinishAll_res($is_auto_import, $factoryId)
    {
        $whereRaw = '1=1 ';
        if ($is_auto_import > 0) {
            $whereRaw .= " and o.is_auto_import={$is_auto_import} ";
        }
        if ($factoryId > 0) {
            $whereRaw .= " and o.factory_id={$factoryId} ";
        }
        $time_list = [];
        $time_list['7']['begin'] = mktime(0, 0, 0, date('m'), date('d') - 7, date('Y'));
        $time_list['7']['end'] = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        $time_list['14']['begin'] = mktime(0, 0, 0, date('m'), date('d') - 14, date('Y'));
        $time_list['14']['end'] = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        $time_list['21']['begin'] = mktime(0, 0, 0, date('m'), date('d') - 21, date('Y'));
        $time_list['21']['end'] = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;

        $result = [
            'all' => $this->_getDeliverNotFinishAll_min('all', $whereRaw),
            'days_avg_7' => $this->_getDeliverNotFinishAll_min('avg', $whereRaw, $time_list['7']['begin'], $time_list['7']['end'], 7),
            'days_avg_14' => $this->_getDeliverNotFinishAll_min('avg', $whereRaw, $time_list['14']['begin'], $time_list['14']['end'], 14),
            'days_avg_21' => $this->_getDeliverNotFinishAll_min('avg', $whereRaw, $time_list['21']['begin'], $time_list['21']['end'], 21),
            'yali' => [],
        ];
        $result['yali'][7]['all']['jianshu'] = sprintf("%.2f", $result['days_avg_7']['avg']['all']['jianshu'] <= 0 ? 0 : $result['all']['all']['jianshu'] / $result['days_avg_7']['avg']['all']['jianshu']);
        $result['yali'][7]['all']['money'] = sprintf("%.2f", $result['days_avg_7']['avg']['all']['money'] <= 0 ? 0 : $result['all']['all']['money'] / $result['days_avg_7']['avg']['all']['money']);
        $result['yali'][7]['zhenzhi']['jianshu'] = sprintf("%.2f", $result['days_avg_7']['avg']['zhenzhi']['jianshu'] <= 0 ? 0 : $result['all']['zhenzhi']['jianshu'] / $result['days_avg_7']['avg']['zhenzhi']['jianshu']);
        $result['yali'][7]['zhenzhi']['money'] = sprintf("%.2f", $result['days_avg_7']['avg']['zhenzhi']['money'] <= 0 ? 0 : $result['all']['zhenzhi']['money'] / $result['days_avg_7']['avg']['zhenzhi']['money']);
        $result['yali'][7]['shuozhi']['jianshu'] = sprintf("%.2f", $result['days_avg_7']['avg']['shuozhi']['jianshu'] <= 0 ? 0 : $result['all']['shuozhi']['jianshu'] / $result['days_avg_7']['avg']['shuozhi']['jianshu']);
        $result['yali'][7]['shuozhi']['money'] = sprintf("%.2f", $result['days_avg_7']['avg']['shuozhi']['money'] <= 0 ? 0 : $result['all']['shuozhi']['money'] / $result['days_avg_7']['avg']['shuozhi']['money']);

        $result['yali'][14]['all']['jianshu'] = sprintf("%.2f", $result['days_avg_14']['avg']['all']['jianshu'] <= 0 ? 0 : $result['all']['all']['jianshu'] / $result['days_avg_14']['avg']['all']['jianshu']);
        $result['yali'][14]['all']['money'] = sprintf("%.2f", $result['days_avg_14']['avg']['all']['money'] <= 0 ? 0 : $result['all']['all']['money'] / $result['days_avg_14']['avg']['all']['money']);
        $result['yali'][14]['zhenzhi']['jianshu'] = sprintf("%.2f", $result['days_avg_14']['avg']['zhenzhi']['jianshu'] <= 0 ? 0 : $result['all']['zhenzhi']['jianshu'] / $result['days_avg_14']['avg']['zhenzhi']['jianshu']);
        $result['yali'][14]['zhenzhi']['money'] = sprintf("%.2f", $result['days_avg_14']['avg']['zhenzhi']['money'] <= 0 ? 0 : $result['all']['zhenzhi']['money'] / $result['days_avg_14']['avg']['zhenzhi']['money']);
        $result['yali'][14]['shuozhi']['jianshu'] = sprintf("%.2f", $result['days_avg_14']['avg']['shuozhi']['jianshu'] <= 0 ? 0 : $result['all']['shuozhi']['jianshu'] / $result['days_avg_14']['avg']['shuozhi']['jianshu']);
        $result['yali'][14]['shuozhi']['money'] = sprintf("%.2f", $result['days_avg_14']['avg']['shuozhi']['money'] <= 0 ? 0 : $result['all']['shuozhi']['money'] / $result['days_avg_14']['avg']['shuozhi']['money']);

        $result['yali'][21]['all']['jianshu'] = sprintf("%.2f", $result['days_avg_21']['avg']['all']['jianshu'] <= 0 ? 0 : $result['all']['all']['jianshu'] / $result['days_avg_21']['avg']['all']['jianshu']);
        $result['yali'][21]['all']['money'] = sprintf("%.2f", $result['days_avg_21']['avg']['all']['money'] <= 0 ? 0 : $result['all']['all']['money'] / $result['days_avg_21']['avg']['all']['money']);
        $result['yali'][21]['zhenzhi']['jianshu'] = sprintf("%.2f", $result['days_avg_21']['avg']['zhenzhi']['jianshu'] <= 0 ? 0 : $result['all']['zhenzhi']['jianshu'] / $result['days_avg_21']['avg']['zhenzhi']['jianshu']);
        $result['yali'][21]['zhenzhi']['money'] = sprintf("%.2f", $result['days_avg_21']['avg']['zhenzhi']['money'] <= 0 ? 0 : $result['all']['zhenzhi']['money'] / $result['days_avg_21']['avg']['zhenzhi']['money']);
        $result['yali'][21]['shuozhi']['jianshu'] = sprintf("%.2f", $result['days_avg_21']['avg']['shuozhi']['jianshu'] <= 0 ? 0 : $result['all']['shuozhi']['jianshu'] / $result['days_avg_21']['avg']['shuozhi']['jianshu']);
        $result['yali'][21]['shuozhi']['money'] = sprintf("%.2f", $result['days_avg_21']['avg']['shuozhi']['money'] <= 0 ? 0 : $result['all']['shuozhi']['money'] / $result['days_avg_21']['avg']['shuozhi']['money']);

        //数据补0
        foreach ($result['yali'] as $k => $v) {
            foreach ($v as $k2 => $v2) {
                foreach ($v2 as $k3 => $v3) {
                    if (strlen($v3) == 3) {
                        $result['yali'][$k][$k2][$k3] = "00{$v3}";
                    }
                    if (strlen($v3) == 4) {
                        $result['yali'][$k][$k2][$k3] = "0{$v3}";
                    }
                    if (strlen($v3) == 5) {
                        $result['yali'][$k][$k2][$k3] = "{$v3}";
                    }
                }
            }
        }
        return $result;
    }

    public function getDeliverNotFinishAll_all_factory()
    {
        $is_auto_import = $this->request->param('from/d', 0);
        $factoryKV = getFactoryKV();
        $result = [];
        foreach ($factoryKV as $k => $v) {
            $temp = $this->getDeliverNotFinishAll_res($is_auto_import, $k);
            //数据显示处理
            $temp['all']['all']['jianshu'] = number_format($temp['all']['all']['jianshu'], 0);
            $temp['all']['all']['money'] = number_format($temp['all']['all']['money'], 2);

            $temp['days_avg_7']['avg']['all']['jianshu'] = number_format($temp['days_avg_7']['avg']['all']['jianshu'], 2);
            $temp['days_avg_7']['avg']['all']['money'] = number_format($temp['days_avg_7']['avg']['all']['money'], 2);

            $temp['days_avg_14']['avg']['all']['jianshu'] = number_format($temp['days_avg_14']['avg']['all']['jianshu'], 2);
            $temp['days_avg_14']['avg']['all']['money'] = number_format($temp['days_avg_14']['avg']['all']['money'], 2);

            $temp['days_avg_21']['avg']['all']['jianshu'] = number_format($temp['days_avg_21']['avg']['all']['jianshu'], 2);
            $temp['days_avg_21']['avg']['all']['money'] = number_format($temp['days_avg_21']['avg']['all']['money'], 2);

            $result[$k] = $temp;
        }
        return json(['code' => 1, 'msg' => '', 'data' => $result]);
    }

    /**
     * 订单进度统计数据--就是在途产能的订单
     * 总定义：
     * 下单----打标----可裁剪---裁剪完成---车缝完成---尾部完成---发货完成（总完成）
     * 采购中：没一个面料没打标。的订单。
     * 面料处理：有一个面料打标，母单不可裁剪。的订单
     * 裁剪中：母单可裁剪，母单没裁剪完。的订单
     * 车缝中：母单裁剪完，车间未完。的订单
     * 尾部中：车间完成，尾部未完。的订单
     * JIT数：已发货的订单
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/26
     */
    public function ddjd()
    {
        $param = [
            'unit' => $this->request->param('unit', 'day'),
            'factory_id' => $this->request->param('factory_id/d', 0),
            'is_auto_import' => $this->request->param('from/d', 0),
            'date_type' => '7_days',
        ];
        $all_7_data = [
            'caigou' => [
                'highcharts_data' => [],
            ],
            'mianliao' => [
                'highcharts_data' => [],
            ],
            'caijian' => [
                'highcharts_data' => [],
            ],
            'chefen' => [
                'highcharts_data' => [],
            ],
            'tail' => [
                'highcharts_data' => [],
            ],
        ];
        $dayly_service = new Daily;
        $dayly_service->temp = [];
        foreach ($all_7_data as $k => $v) {
            $param['type'] = $k;
            $all_7_data[$k]['highcharts_data'] = $dayly_service->chart_ddjd($param);
        }
        $whereRaw = '';
        if ($param['is_auto_import'] > 0) {
            $whereRaw .= " and o.is_auto_import={$param['is_auto_import']} ";
        }
        if ($param['factory_id'] > 0) {
            $whereRaw .= " and o.factory_id={$param['factory_id']} ";
        }
        $sql = "SELECT   om.order_id,o.client_ordernum
,max(om.caigou_confirm_status) as caigou_confirm_status_max 
,min(om.caigou_confirm_status) as caigou_confirm_status_min
,max(om.caichuang_can_do) as caichuang_can_do_max
,min(om.caichuang_can_do) as caichuang_can_do_min
,o.caichuang_can_do,o.caichuang_status,o.chejian_status,o.tail_status
,min(if(om.caigou_confirm_time > 0,om.caigou_confirm_time,9999999999)) as caigou_confirm_time_min
,o.caichuang_can_do_time,o.caichuang_over_time,o.chejian_over_time,o.tail_over_time
,o.quantity
FROM wx_order_material om
LEFT JOIN wx_order o on (om.order_id=o.id)
LEFT JOIN wx_material m on (om.material_id=m.id)
WHERE o.status in (0,1) and o.client_status <> 99  {$whereRaw}
and m.type <> 'accessories'
GROUP BY om.order_id";
        $list = db()->query($sql);
        $res = [
            'caigou' => [//采购中
                'all' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'yestoday' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'highcharts_data' => [],
            ],
            'mianliao' => [//面料处理中
                'all' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'yestoday' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'highcharts_data' => [],
            ],
            'caijian' => [//裁剪中
                'all' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'yestoday' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'highcharts_data' => [],
            ],
            'chefen' => [//车缝中
                'all' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'yestoday' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'highcharts_data' => [],
            ],
            'tail' => [//尾部中
                'all' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'yestoday' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
                'highcharts_data' => [],
            ],
            'jit' => [//JIT
                'all' => [
                    'jian' => 0,//件数
                    'num' => 0,//单数
                ],
            ],
        ];
        foreach ($list as $k => $v) {
            if ($v['caigou_confirm_status_max'] == 0) {
                $res['caigou']['all']['num']++;
                $res['caigou']['all']['jian'] += $v['quantity'];
            }
            if ($v['caigou_confirm_status_max'] == 1 && $v['caichuang_can_do'] == 0) {
                $res['mianliao']['all']['num']++;
                $res['mianliao']['all']['jian'] += $v['quantity'];
            }
            if ($v['caichuang_can_do'] == 1 && $v['caichuang_status'] == 0) {
                $res['caijian']['all']['num']++;
                $res['caijian']['all']['jian'] += $v['quantity'];
            }
            if ($v['caichuang_status'] == 1 && $v['chejian_status'] == 0) {
                $res['chefen']['all']['num']++;
                $res['chefen']['all']['jian'] += $v['quantity'];
            }
            if ($v['chejian_status'] == 1 && $v['tail_status'] == 0) {
                $res['tail']['all']['num']++;
                $res['tail']['all']['jian'] += $v['quantity'];
            }
        }
        list($res['caigou']['yestoday']['num'], $res['caigou']['yestoday']['jian']) = $this->_ddjd_yestoday($dayly_service->temp, 'caigou');
        list($res['mianliao']['yestoday']['num'], $res['mianliao']['yestoday']['jian']) = $this->_ddjd_yestoday($dayly_service->temp, 'mianliao');
        list($res['caijian']['yestoday']['num'], $res['caijian']['yestoday']['jian']) = $this->_ddjd_yestoday($dayly_service->temp, 'caijian');
        list($res['chefen']['yestoday']['num'], $res['chefen']['yestoday']['jian']) = $this->_ddjd_yestoday($dayly_service->temp, 'chefen');
        list($res['tail']['yestoday']['num'], $res['tail']['yestoday']['jian']) = $this->_ddjd_yestoday($dayly_service->temp, 'tail');
        //JIT数据设置
        $sql = "SELECT   
sum(IFNULL(od.delivery_count, 0)) as sum_count
,count(distinct od.order_id) as count_order_id
FROM wx_order_delivery od
LEFT JOIN wx_order o on (o.id=od.order_id)
where 
o.status in (0,1) and o.client_status <> 99 {$whereRaw}
and od.delivery_status not in (6,7)";
        $info = db()->query($sql);
        $res['jit']['all']['num'] = $info[0]['count_order_id'];
        $res['jit']['all']['jian'] = $info[0]['sum_count'];
        return json(['code' => 0, 'msg' => '', 'data' => [
            'table' => $res,
            'highcharts_data' => $all_7_data
        ]]);
    }

    private function _ddjd_yestoday($data, $type = '')
    {
//        $yestoday = date('Y-m-d', time() - 1 * 24 * 3600);
        $today = date('Y年m月d日', time());
        foreach ($data[$type] as $k => $v) {
            if ($v['sdate'] == $today) {
                return [
                    $v['num_order'], $v['num']
                ];
            }
        }
        return [0, 0];
    }

    public function ddjdTableDetail()
    {
        $is_auto_import = $from = $this->request->param('from/d', 0);
        $factoryId = $this->request->param('factory_id/d', 0);
        $types = $this->request->param('types', '');
        //2,数据查询
        if ($this->request->isAjax()) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $whereRaw = '1=1 ';
            if ($is_auto_import > 0) {
                $whereRaw .= " and o.is_auto_import={$is_auto_import} ";
            }
            if ($factoryId > 0) {
                $whereRaw .= " and o.factory_id={$factoryId} ";
            }
            $havingWhere = '';
            switch ($types) {
                case 'caigou':
                    $havingWhere == '' && $havingWhere = 'caigou_confirm_status_max=0';
                case 'mianliao':
                    $havingWhere == '' && $havingWhere = 'caigou_confirm_status_max=1 and caichuang_can_do=0';
                case 'caijian':
                    $havingWhere == '' && $havingWhere = 'caichuang_can_do=1 and caichuang_status=0';
                case 'chefen':
                    $havingWhere == '' && $havingWhere = 'caichuang_status=1 and chejian_status=0';
                case 'tail':
                    $havingWhere == '' && $havingWhere = 'chejian_status=1 and tail_status=0';
                    $whereRaw .= " and o.status in (0,1) and o.client_status <> 99
and m.type <> 'accessories' ";
                    $list = db('order_material om')
                        ->field('o.id,o.client_ordernum,o.order_price,o.quantity as sum_count,o.create_time
                            ,o.status as order_status,o.caigou_status,o.real_shipment_status
                            ,ft.name as ft_name
                            
                            ,max(om.caigou_confirm_status) as caigou_confirm_status_max 
,min(om.caigou_confirm_status) as caigou_confirm_status_min
,max(om.caichuang_can_do) as caichuang_can_do_max
,min(om.caichuang_can_do) as caichuang_can_do_min
,o.caichuang_can_do,o.caichuang_status,o.chejian_status,o.tail_status

,min(if(om.caigou_confirm_time > 0,om.caigou_confirm_time,1999999999)) as caigou_confirm_time_min
,o.caichuang_can_do_time,o.caichuang_over_time,o.chejian_over_time,o.tail_over_time
,o.quantity
                            ')
                        ->join('order o', 'om.order_id=o.id', 'left')
                        ->join('factory ft', 'ft.id=o.factory_id', 'left')
                        ->join('material m', 'om.material_id=m.id', 'left')
                        ->whereRaw($whereRaw)
                        ->page($page)
                        ->limit($limit)
                        ->order("o.id desc")
                        ->group('om.order_id')
                        ->having($havingWhere)
                        ->select();
                    foreach ($list as $k2 => $v2) {
                        $list[$k2]['create_time'] = date('Y-m-d H:i:s', $list[$k2]['create_time']);
                        $list[$k2]['status_txt'] = $this->_get_order_status_txt($v2);
                    }
                    $data['count'] = db('order_material om')
                        ->field('max(om.caigou_confirm_status) as caigou_confirm_status_max 
                            ,o.caichuang_can_do,o.caichuang_status,o.chejian_status,o.tail_status')
                        ->join('order o', 'om.order_id=o.id', 'left')
                        ->join('factory ft', 'ft.id=o.factory_id', 'left')
                        ->join('material m', 'om.material_id=m.id', 'left')
                        ->whereRaw($whereRaw)
                        ->group('om.order_id')
                        ->having($havingWhere)
                        ->count();
                    $data['data'] = $list;
                    $data['code'] = 0;
                    $data['msg'] = '';
                    return json($data);
                    break;
                case 'jit':
                    $whereRaw .= " and o.status in (0,1) and o.client_status <> 99
                    and od.delivery_status not in (6,7) ";
                    $list = db('order_delivery od')
                        ->field('od.id,o.client_ordernum,o.order_price,o.quantity,o.create_time
                            ,o.status as order_status,o.caigou_status,o.caichuang_status,o.chejian_status,o.tail_status,o.real_shipment_status
                            ,o.is_new
                            ,ft.name as ft_name
                            ,od.delivery_time,od.delivery_number,od.delivery_status,od.delivery_count as sum_count
                            ')
                        ->join('order o', 'o.id=od.order_id', 'left')
                        ->join('factory ft', 'ft.id=o.factory_id', 'left')
                        ->whereRaw($whereRaw)
                        ->page($page)
                        ->limit($limit)
                        ->order("o.id desc")
                        ->select();
                    $delivery_status = config('mimo.delivery_status');
                    foreach ($list as $k2 => $v2) {
                        $list[$k2]['create_time'] = date('Y-m-d H:i:s', $list[$k2]['delivery_time']);
                        $list[$k2]['status_txt'] = $delivery_status[$v2['delivery_status']];
                    }
                    $data['count'] = db('order_delivery od')
                        ->join('order o', 'o.id=od.order_id', 'left')
                        ->join('factory ft', 'ft.id=o.factory_id', 'left')
                        ->whereRaw($whereRaw)
//                        ->group('od.order_id')
                        ->count();
                    $data['data'] = $list;
                    $data['code'] = 0;
                    $data['msg'] = '';
                    return json($data);
                    break;
            }
        }
        $this->assign('thisFrom', $from);
        $this->assign('thisFactoryId', $factoryId);
        $this->assign('types', $types);
        return $this->fetch('ddjd_table_detail');
    }
}